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

后端 未结 3 1196
南笙
南笙 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.

    0 讨论(0)
  • 2021-02-19 19:59

    You have to construct your base class before dealing with derived. If you construct your derived class with non-trivial constructors, compiler cannot decide what to call for base, that's why error is occuring.

    0 讨论(0)
  • 2021-02-19 20:03

    Constructors are not inherited. You have to create a constructor for the derived class. The derived class's constructor, moreover, must call the base class's constructor.

    0 讨论(0)
提交回复
热议问题