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?