Why is it necessary for parent class to have a default constructor if we create constructor in child class [duplicate]

Is it obligatory to have a default constructor in a superclass to have the possibility to inherit from it? Suppose every derived class constructor is calling one of superclass constructors explicitly, providing the right parameters - will such code work?


Solution 1:

is it obligatory to have a default constructor in a superclass to have the possibility to inherit from it?

No.

If you don't have default constructor in the base class, you need to call the base class constructor with argument(s) explicitly from the derived class constructor's member-initialization list.

Example,

class base
{
   public:
     base(std::string const & s, int n);
};

class derived : public base
{
   anotherClass obj;
   public:
     derived() : base("string", 10), obj(100) 
     {       //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ member-initialization list
     }
};

Note the syntax of base("string", 10). It invokes the base class's constructor, passing "string" as first argument and 10 as second argument.

Also notice obj(100) which initializes the member variable which is of type anotherClass : obj(10) invokes the constructor of anotherClass which takes int as argument.

Solution 2:

Provided that

  • The default constructor is not called explicitely
  • All subclasses invoke on construction the user-defined super-class constructor with parameters

it is not mandatory to write a default constructor.

Solution 3:

If every constructor of the children classes use an explicit constructor of the parent, there is no need for the parent to have a default constructor.

If you have a class with no default constructor, everyone is forced to use an explicit constructor upon instantiation, right? It's the same concept, if all the children make sure the default constructor is never called, then there is no need to implement it.

Solution 4:

No, with one possible exception. Normally, the base class constructor will be called by the derived class immediatly above it, using the arguments provided by that derived class (if any). If all of the immediate derived classes initialize the base class explicitly, then no default constructor is needed.

The one possible exception is if you inherit virtually from the base class. In that case, it is not the immediate derived class which initializes the base class, but the most derived class. And depending on how your class hierarchy is organized, you may not want the most derived class to know about the base; it should be sufficient for the most derived class to only know about the classes it directly inherits from. (Of course, this is an ideal, and is not always the case.) Luckily, as it happens, almost every time this occurs, the base is an abstract class without data (and thus with a default constructor). But it's something to keep in mind.