I have the following simple code:
class A
{
int a;
public:
A(int a) : a(a) { cout << "Constructor a=" << a << endl; }
~A() { cout << "Destructor a=" << a << endl; }
void print() { cout << "Print a=" << a << endl; }
};
void f()
{
A a(1);
a.print();
a = A(2);
a.print();
}
int main()
{
f();
return 0;
}
The output is:
Constructor a=1
Print a=1
Constructor a=2
Destructor a=2
Print a=2
Destructor a=2
I find that there are two destructor calls with a=2
and none with a=1
while there is one constructor call for each case. So how are contructors and destructros called in this case?
a = A(2);
Will use default operator=
to assign new value to a
, setting it's a::a
member value to 2.
void f()
{
A a(1);//a created with int constructor a.a == 1
a.print();// print with a.a == 1
a = A(2);//Another A created with int constructor setting a.a == 2 and immediately assigning that object to a
//object created with A(2) deleted printing 2 it was created with
a.print();//a.a==2 after assign
}//a deleted printing 2 it was assigned with
You probably should read about Rule of three to get better understanding what's going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With