Vasile Turcu Vasile Turcu - 3 months ago 21
C++ Question

C++ Constructor Oder

Consider the following piece of code:

#include<iostream>
using namespace std;
class cls
{
public:
cls(int i=0) {cout<<" c1 ";}
~cls() {cout<<" d 1 ";}
};
class cls2
{
cls xx;
public:
cls1(int i=0){cout<<" c2 ";}
~cls1(){cout<<" d2 ";}
}c;
class cls3
{
cls2 xx; cls xxx;
public:
cls2(int i=0) {cout<<" c3 ";}
~cls2(){ cout<<" d3 ";}
};
int main()
{
cls3 s;
return 0;
}


Now, when I run it, it outputs:


c1 c2 c1 c2 c1 c3 d3 d1 d2 d1 d2 d1


and I can't seem to figure out why, in my head, it should output:


c1 c2 c1 c3 d3 d1 d2 d1


because:

cls2 s -> cls1 xx -> cls xx => c1
=> c2
-> cls xxx => c1
=> c3


I know that somewhere, my logic is flawed, but I don't know where.

Answer

You are creating an extra global instance c here:

class cls1
{
    int x; cls xx;
public:
        cls1(int i=0){cout<<" c2 ";x=i;}
        ~cls1(){cout<<" d2 ";}
} c; // <-- here

That one is created first.

Otherwise your expected order is spot-on.

Comments