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?
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.
The reason why default constructor is called is that in case if you have created any object and at that instance you have not passed arguments (you may want to initialize them later in the program). This is the most general case, that's why calling default constructor is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With