Search code examples
c++inheritancesubclasssubclassing

Does a subclass need a default constructor?


I am learning about inheritance right now, and there is one thing I haven't found a solid answer on. If I have three classes one being a super and two subclass, would my subclasses need a default constructor if they inherit the same fields? Class b doesn't have a default constructor because it inherits its fields from A, where as class c has different fields, therefore it would need its own default constructor.

class A {
  
    private:
        int a;
        int b;
    
    public:
        A();
        A(int, int);
    
};

class B: public A {
  
    public:
        B(int, int);
    
};

class C : public A {
  
    private:
        int c;
    
    public:
        C();
        C(int, int);
    
};

anything is greatly appreciated.


Solution

  • If [irrelevant], would my subclasses need a default constructor if [irrelevant]?

    That depends on how your subclasses are used. If – and only if – you need to construct an instance of your class without providing construction parameters, then that class needs a default constructor. Whether or not you need to explicitly define (or forward via using) a default constructor depends on whether or not other constructors are defined, and on whether or not that constructor has something non-trivial to do. This topic should have been covered long before inheritance.

    There is, however, a new caveat when inheritance enters the picture. Since I cannot tell if you use member initialization lists, I recommend reading No Matching Function Call to Base class. If you do not use member initialization lists, your derived classes will construct their bases without construction parameters. However, note that it is usually better to address this situation by using initialization lists rather than adding a default constructor.

    Class b doesn't have a default constructor because it inherits its fields from A,

    No, class B doesn't have a default constructor because it defines a non-default constructor. The non-default constructor prevents the compiler from supplying a default constructor. If your code successfully compiles, one can conclude that B does not need a default constructor.

    where as class c has different fields, therefore it would need its own default constructor.

    Whether or not a class has fields is irrelevant to "need". (Fields may make it more likely that an explicit default constructor is appropriate since there might be data to initialize, but their mere existence does not dictate a need.)