Is this out of scope?

I have been testing this code for about an hour now, and still do not get why it fails. When I try it in a test program it works, but in the normal program it fails.

test code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class a {
public:
	string c;
	
	a() {
		string a[]={"hello", "hi"};
		c=a[1];
	}
};
	

int main() {
	a h;
	cout<<h.c;	//in test code, it works
				//in actual program the same concept fails
}

thanks in advance
Define "doesn't work".

Also, this sort of thing means that you are using the class wrong in your normal program. How are you using it?
closed account (S6k9GNh0)
I'm not sure what you mean...
http://liveworkspace.org/code/4mOCzS$2
in the test the output is "hi", but in the normal program it is a blank line. The test code uses has exactly the same semantics as the test code:
1) in class constructor assign string variable to member of array
2) instantiate new class
3) output variable
It would be good if we would know whar you mean saying the code fails.

Please show a compiled example that everybody could reproduce the behavior.
Last edited on
As I explained above, in the test unit the program outputs "hi", while in the normal program it outputs a blank line.
Either post an example that replicates the error or post the original code.
Please show a compiled example that everybody could reproduce the behavior
As I explained above, in the test unit the program outputs "hi", while in the normal program it outputs a blank line.


If you simplify code until an issue no longer occurs with it, you've very likely removed the source of the issue. How, then, are we supposed to advise you about the error when the code provided doesn't produce it?
Ah, I seemed to have left out a very important detail (very sorry). Still od not understand why it does not work though. New test unit code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class a {
public:	
	string c;
	int b;
	a(int p) {
		string a[]={"hello", "hi"};
		c=a[1];
		b=p;
	}
	
	a() { a(0); }
};
	

int main() {
	a h;
	cout<<h.c;	//in test code, it works
				//in actual program the same concept fails
}
closed account (S6k9GNh0)
http://liveworkspace.org/code/4mOCzS$7

Your example doesn't work because you're clearly not calling the correct constructor. Again, I don't understand the problem outside of that.
I have got a picture, how do I share it with all of you?
This is what I get with my compiler:
http://liveworkspace.org/code/4dufSF$2

EDIT:
And this is what my previous code gives:
http://liveworkspace.org/code/4dufSF$4
Last edited on
a() { a(0); }

This creates a temporary object which is immediately destroyed, it does nothing to any data member of the a being constructed.

If your compiler supports delegating constructors:

a() : a(0) {}

For this simple example you could get rid of the default constructor and go with

a(int p=0) { ...
Last edited on
I understand now, thank you to those that helped :)
Topic archived. No new replies allowed.