Inheriting constructors

前端 未结 6 2172
无人及你
无人及你 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:58

    Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

    The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

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

    UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

提交回复
热议问题