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
D d = D();
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 object d
is destroyed when it goes out of scope, after main()
is completed.
If you add a copy constructor to D
you'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.
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