C++ Constructor Oder [closed]

2019-09-21 12:25发布

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.

1条回答
姐就是有狂的资本
2楼-- · 2019-09-21 13:10

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.

查看更多
登录 后发表回答