C++ Primer (5th edition) on page 629 states:
A class that contains only inherited constructors will have a synthesized default constructor.
What is the reasoning behind this rule?
The default constructor in the Person class is not inherited by Employee and therefore a default constructor must be provided in Employee, either automatically by the compiler or coded by the developer.
In C++, the compiler creates a default constructor if we don't define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members.
Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
I think that quote can be misgiving. The following, for example, will not compile:
struct Base{
Base(int){}
};
struct Derived : Base{
using Base::Base;
};
int main()
{
Derived d; // error: Derived has no public default ctor!!!
}
Derived
contains only inherited constructors, but it does not have a public default one! I said public! Actually, the error message from gcc
is:
'Derived::Derived()' is implicitly deleted because the default definition would be ill-formed
So, what the author means is that if a Derived
class inherit constructors from a Base
class, a default constructor for Derived
will be provided, because it may have to default initialize Derived
's data member that can't be initialized from inherited constructors, because they even don't know of their existence.
Finally, in my example the default ctor for Derived has been implicitly deleted by the compiler, because no one explicitly defined it. But if you add a default ctor to Base, the synthesized default ctor for Derived will be available.
If the base class does not contain a constructor without parameters, then the compiler would not be able to generate a default constructor for the derived class because it needs the missing arguments for the constructors of the base class. However, if base class contains a default constructor or a constructor that does not take any parameters, then a default constructor for the derived class can be generated with the usual purpose of calling constructors of the member variables. The purpose is the convenience not to write an empty constructor yourself if the constructor doesn't do anything special.
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