I tried the following program on Visual Studio 2010.
#include <iostream>
using namespace std;
class A {
public:
int p;
/*A(){
cout << "Constructor A" << endl;
}*/
~A(){
cout << "Destructor in A" << endl;
}
};
class D: public A
{
public:
/*D(){
cout << "Constructor D" << endl;
}*/
~D(){
cout << "Destructor in D" << endl;
}
};
int main()
{
D d = D();
cout << "Exiting main" << endl;
}
The output that I got was –
Destructor in D
Destructor in A
Exiting main
Destructor in D
Destructor in A
I am not able to understand why the destructor of class D and A are being called
before “Exiting main” statement is executed?
I tried another thing – I uncommented the Class D constructor in the code above, then the output was as I
expected –
Constructor D
Exiting main
Destructor in D
Destructor in A
What am I missing here?
The line
first creates a temporary, unnamed object, which then is copied to
d. What you see is the temporary object being destroyed when the statement is ended. The named objectdis destroyed when it goes out of scope, aftermain()is completed.If you add a copy constructor to
Dyou’ll see that it is invoked.When commenting out the constructor I think that you see the expected behaviour because the compiler can do some optimizations.