Mock
Mock

Reputation: 379

Destructor and Constructor Ordering in C++

I have a short block of code as follows:

#include <iostream>

using namespace std;

class C {
public:
    C() {i = 6; cout << "C0:" << i << endl;}

    C(int i0) {i = i0; cout << "C1:" << i << endl;}

    ~C() {cout << "C2:" << i << endl;}
private:
    int i;
};

class D {
public:
    D() {cout << "D0" << endl;}
    ~D() {cout << "D1" << endl;}
private:
    C c;
};

int main(int argc, char* argv[]) {
    cout << "X" << endl;
    D d;
    cout << "Y" << endl;
}

The output of which is:

X
C0:6
D0
Y
D1
C2:6

My question is: why would the C0:6 be created before the D0 in this case?

I know that for an inherited class, the order is Base Constructor->Derived Constructor->Derived Destructor->Base Destructor. So, if D was inherited from C, then I would expect the ordering here. However, D is not a subclass of C, from what I can tell; it simply contains an instance of the C class.

So in this case, why do I get the same output ordering as if D was a subclass of C?

There's clearly a fundamental rule I'm not understanding.

Upvotes: 1

Views: 637

Answers (1)

M.M
M.M

Reputation: 141544

The base class objects and member variables (in that order) are initialized before the statements in the constructor body are executed.

c is a member of D, so you see c's initialization before D's constructor body.

Destruction occurs in the opposite order of construction.

Upvotes: 4

Related Questions