Home > Back-end >  Sequence of Constructors and Destructors when base class type member variable is initialized through
Sequence of Constructors and Destructors when base class type member variable is initialized through

Time:12-27

while I'm writing some code regarding base class/derived class type variables, I encountered this somewhat weird situation. It goes like this :

#include <iostream>

using namespace std;

class A {
public:
    A() { cout << "A Con" << endl; }
    virtual ~A() { cout << "A Dec" << endl; }
};
class B : A {
public:
    A a;
    B(A _a) : a(_a) { 
        cout << "B Con" << endl;
    }
    virtual ~B() { cout << "B Dec" << endl; }    
};

int main()
{
    A a;
    B b(a);
}

I declared base class(A) type member variable in derived class(B), and then above code gives me this result :

enter image description here

OK, so first constructor and last constructor would be for 'a' in main function. But what about the others? why destructors are called 5 times while constructors are only called 3?

My Guess is :

A Con -> a in main()
A Con -> b in main() (base class constructor)
B Con -> b in main() (derived class constructor)
A Dec -> temporary value passed in B(A _a) : a(_a), copy constructor is called...
B Dec -> b in main() (derived class destructor)
A Dec -> member variable in B class (A a;)
A Dec -> b in main() (base class destuctor)
A Dec -> a in main()

Am I right or wrong?

CodePudding user response:

This:

B(A _a) : a(_a) { 
    cout << "B Con" << endl;
}

calls A's copy constructor, which you have not defined and which does not print anything. Add this to A:

A(A const&) { cout << "A Con (Copy)" << endl; }

And while you're at it, you may want A(A&&), A& operator=(A const&) and A& operator=(A&&) as well.

  • Related