Why does my C++ subclass need an explicit constructor?

后端 未结 3 1204
南笙
南笙 2021-02-19 19:12

I have a base class that declares and defines a constructor, but for some reason my publicly derived class is not seeing that constructor, and I therefore have to explicitly dec

3条回答
  •  天命终不由人
    2021-02-19 19:48

    All the derived classes must call their base class's constructor in some shape or form.

    When you create an overloaded constructor, your default compiler generated parameterless constructor disappears and the derived classes must call the overloaded constructor.

    When you have something like this:

    class Class0 {
    }
    
    class Class1 : public Class0 {
    }
    

    The compiler actually generates this:

    class Class0 {
    public:
      Class0(){}
    }
    
    class Class1 : public Class0 {
      Class1() : Class0(){}
    }
    

    When you have non-default constructor, the parameterless constructor is no longer generated. When you define the following:

    class Class0 {
    public:
      Class0(int param){}
    }
    
    class Class1 : public Class0 {
    }
    

    The compiler no longer generates a constructor in Class1 to call the base class's constructor, you must explicitly do that yourself.

提交回复
热议问题