Inheriting constructors

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

    If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

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

    This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

    Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

提交回复
热议问题