Can I call a constructor from another one ? I loose data !

Hi,

The following code fails, but I don't understand why :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Titi {
public:
	int* pMyInts;
	Titi() {
		pMyInts = new int[2];
	}
	Titi(int a0, int a1) {
		Titi();
		pMyInts[0] = a0;
		pMyInts[1] = a1;
	}
	~Titi() {
		delete [] pMyInts;
	}
};

int main(int argc, const char *argv[]) {
	cout << "Test a constructor with parameters that call a custom constructor with no parameters but that has the charge to allocate memory for pointers on arrays with new" << endl;
	Titi t(5,7);
	cout << "\tTiti t(5,7) = " << t.pMyInts[0] << " " << t.pMyInts[1] << endl;

	return 0;
}

At runtime, the first cout is printed and nothing else.

At debug, I can see that when I exit Titi(), pMyInts loose its value. What explains this code fails. But why does it loose its value ? I cannot figure out what I do wrong.

Please, could you give me some insight ?
You cannot call a constructor this way (the upcoming version 11 alows calling another constructor but different).

line 8 creates only a local variable and has no influence to the surrounding constructor
Here in the code

1
2
3
4
5
	Titi(int a0, int a1) {
		Titi();
		pMyInts[0] = a0;
		pMyInts[1] = a1;
	}


you create unnamed temporary object which will be deleted in the same statement after ; So the next code has undefined behavior because you did not allocate memory for pMyInts.
I suppose this works:
1
2
3
4
5
6
7
8
9
10
class Test {
public: 
	int* ints;
	Test() { ints = new int[2]; }
	Test(int a, int b) {
		*this = Test();
		ints[0] = a;
		ints[1] = b;
	}
};

Seems like consciously aiming at your foot with your finger trembling on the trigger, to be honest.
Thanks a lot all three of you. That increase deeply my understanding of C++.
If I am right, *this = Test(); makes a copy which may be a drawback for big classes. If I am still right, the following avoid it :

1
2
3
4
5
6
7
8
9
10
11
12
13
class Titi {
public:
	int* pMyInts;
	void init(Titi& t) {t.pMyInts = new int[2];}
	Titi(int a0, int a1) {
		init(*this);
		pMyInts[0] = a0;
		pMyInts[1] = a1;
	}
	~Titi() {
		delete [] pMyInts;
	}
};

Gaminic.

this code *this = Test(); can work only then the compiler uses optimization and does not create a temporary object Test(). Otherwise destructor will be called and it will delete the pointer. So in general this code has undefined behavior.
Topic archived. No new replies allowed.