Derived Class Constructor Calls

kjh picture kjh · Nov 19, 2012 · Viewed 20.2k times · Source

If I have a base class:

class Base{
  ...
};

and a derived class

class Derived : public Base{
  ...
}

does this derived class always call the default constructor of the base class? i.e. the constructor that takes no parameters? For example If I define a constructor for the base class:

Base(int newValue);

but I do not define the default constructor(the parameterless constructor):

Base();

(I recognize this is only a declaration and not a definition) I get an error, until I define the default constructor that takes no parameters. Is this because the default constructor of a base class is the one that gets called by a derived class?

Answer

Luchian Grigore picture Luchian Grigore · Nov 19, 2012

Yes, by default, the default constructor is called. You can go around this by explicitly calling a non-default constructor:

class Derived : public Base{
    Derived() : Base(5) {}
};

This will call the base constructor that takes a parameter and you no longer have to declare the default constructor in the base class.