Problem about class constructor

When the class constructor called another class constructor, the value of the a,b,c is not changed by the new called class constructor.
I wonder why the new constructor will not change the value of a,b,c. Even that some of the values are not initialized yet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using namespace std;

class work{
	public:
		int a,b,c;
		work(){	//default
			cout << "Default constructor" << endl;
			a=5;
			b=7;
			c=2;
			cout << "Finished." << endl;
			cout << "Memory address in this DEFAULT constructor:" << endl;
			cout << &a << " " << &b << " " << &c  << "\n"<< endl; 
		}
		work(int f, char g, double h){	//type 1
			cout << "Type 1 constructor\n" << endl;
			cout << "Memory address of a,b,c in type 1 constructor:" << endl;
			cout << &a << " " << &b << " " << &c << "\n" << endl;
//			work();	//Whatever where we place the work() will still make no differences
			a=0;
//			b=g;	//Let's don't initialize value of b and try to let the default constructor do (failed)
			c=999;
			work();	//Will still run work() but won't change the value of a,b,c
			cout << "Out of the default constructor." << endl;
			cout << "Memory address of a,b,c in type 1 constructor:" << endl;			
			cout << &a << " " << &b << " " << &c << "\n" << endl;
		}
 
};	

int main(){
	work d;
	work e(3,'a',99);
	cout << "Memory address of d:" << endl;
	cout << &d.a << " " << &d.b << " " << &d.c << endl;
	cout << "Value of d:" << endl;
	cout << d.a << " " << d.b << " " << d.c << endl;	//default
	cout << "Memory address of e:" << endl;
	cout << &e.a << " " << &e.b << " " << &e.c << endl;
	cout << "Value of e:" << endl;
	cout << e.a << " " << e.b << " " << e.c << endl;	//type 1
}
> work(); //Will still run work() but won't change the value of a,b,c
No, what it will do is create ANOTHER instance of work(), initialise those values to the default values, and then almost immediately call the destructor on it because it has no lifetime.

1
2
3
		~work( ) {
                        cout << this << " destroyed" << endl;
                }

Also print the 'this' pointer in your constructors as well, so you know which object instance is in play at that moment.
Thanks for your helping!!
Topic archived. No new replies allowed.