Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ destructor behaviour [duplicate]

Tags:

c++

destructor

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?

like image 913
omggs Avatar asked May 13 '11 06:05

omggs


1 Answers

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.

like image 144
Anders Abel Avatar answered Oct 26 '22 13:10

Anders Abel