1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mock
  • 359
  • 1
  • 3
  • 11
  • 1
    The data members constructed first, then the constructor of the class itself is called. – AlexD Feb 07 '17 at 04:02
  • Try to read this http://stackoverflow.com/questions/2669888/c-initialization-order-for-member-classes – segevara Feb 07 '17 at 04:03
  • Okay, this is what I think I'm taking away from that post: If a class contains other classes, those other classes will have their constructors called first. However, the initial class will still have its destructor called first. Is that correct? – Mock Feb 07 '17 at 04:09
  • Think about it for a moment -- if one of your member subobjects was a vector, your constructor might like to add some items to it. But that wouldn't be possible if the vector hadn't been constructed yet. – Ben Voigt Feb 07 '17 at 04:47

1 Answers1

4

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Worth noting that base class objects and (non-static) member variables are collectively called "subobjects", and get similar treatment in many ways. The differences lead to the "Inheritance vs Composition" question, exactly because they are so nearly interchangable. – Ben Voigt Feb 07 '17 at 04:45