Error : base class constructor must explicitly initialize parent class constructor

后端 未结 5 697
傲寒
傲寒 2021-02-02 07:22

I am new to c++. When I try to compile the code below , I get this error

constructor for \'child\' must explicitly initialize the base class \'parent\' whic

5条回答
  •  天涯浪人
    2021-02-02 07:52

    At the risk of repeating the error message you got: a child class constructor must invoke its parent's constructor.

    The compiler will add an automatic invocation of the parent's default (argumentless) constructor. If the parent does not have a default constructor, you must explicitly invoke one of the constructors it does have by yourself.

    The compiler has to enforce this to ensure that the functionality that the child class has inherited from the parent is set up correctly... for example, initialising any private variables that the child has inherited from the parent, but cannot access directly. Even though your class doesn't have this problem, you must still follow the rules.

    Here are some examples of constructors in classes using inheritance:

    This is fine, ParentA has a default constructor:

    class ParentA
    {
    };
    
    class ChildA
    {
    public:
        ChildA() {}
    };
    

    This is not fine; ParentB has no default constructor, so ChildB1 class must explicitly call one of the constructors itself:

    class ParentB
    {
        int m_a;
    
    public:
        ParentB(int a) : m_a(a) {}
    };
    
    class ChildB1 : public ParentB
    {
        float m_b;
    
    public:
        // You'll get an error like this here:
        // "error: no matching function for call to ‘ParentB::ParentB()’"
        ChildB1 (float b) : m_b(b) {}
    };
    

    This is fine, we're calling ParentB's constructor explicitly:

    class ChildB2 : public ParentB
    {
        float m_b;
    
    public:
        ChildB2(int a, float b) : ParentB(a), m_b(b) {}
    };
    

    This is fine, ParentC has a default constructor that will be called automatically:

    class ParentC
    {
        int m_a;
    
    public:
        ParentC() : m_a(0) {}
        ParentC(int a) : m_a(a) {}
    };
    
    class ChildC: public ParentC
    {
        float m_b;
    
    public:
        ChildC(float b) : m_b(b) {}
    };
    

提交回复
热议问题