首先要构造什么?

时间:2019-05-19 01:52:12

标签: c++ oop polymorphism

我只是想知道这里的结构顺序。  这里首先要构造的是已经调用A的instanceOfA`或B的构造函数?

class A {
    public:
    A() { cout << "A ctor" << endl; }
    A(const A& a) { cout << "A copy ctor" << endl; }
    virtual ~A() { cout << "A dtor" << endl; }
    virtual void foo() { cout << "A foo()" << endl; }
    virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};

class B : public A {
    public:
    B() { cout << "B ctor" << endl; }
    virtual ~B() { cout << "B dtor" << endl; }
    virtual void foo() { cout << "B foo()" << endl; }
    protected:
    A mInstanceOfA; // don't forget about me!
    };

int main() {
    B X;
}

1 个答案:

答案 0 :(得分:1)

构造函数的顺序为:

基础-成员-派生