Inheriting constructors

前端 未结 6 2176
无人及你
无人及你 2020-11-22 09:16

Why does this code:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
};

int main(void)
{
    B *b = new B(5);
    delete b;
}
         


        
6条回答
  •  面向向阳花
    2020-11-22 09:52

    This is straight from Bjarne Stroustrup's page:

    If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:

    struct B1 {
        B1(int) { }
    };
    
    struct D1 : B1 {
        using B1::B1; // implicitly declares D1(int)
        int x;
    };
    
    void test()
    {
        D1 d(6);    // Oops: d.x is not initialized
        D1 e;       // error: D1 has no default constructor
    }
    

提交回复
热议问题