Why is the base constructor called?
Alright, I have a very basic question, so please go easy on me.
In the following code:#include<iostream>
class base
{
public:
base() { std::cout << "Base()" << std::endl; }
};
开发者_运维知识库class derived: base {
public:
derived() { std::cout << "Derived()" << std::endl; }
};
int main() {
derived d;
}
The output is:
Base()
Derived()
I would like to know why the constructor of the base
class is called even though I am creating an object of the derived
class? I could not find a proper answer in the FAQ
.
Constructor of the base
class is called to initialize base
class subobject that contained in the derived
. This is how inheritance works, this makes it easier to follow the Liskov substitution principle.
Consider the following:
class base
{
public:
base() : x(10) { std::cout << "Base()" << std::endl; }
private:
int x;
};
class derived: base {
public:
derived() { std::cout << "Derived()" << std::endl; }
};
How you would initialize member base::x
without calling constructor of the base class?
Nevertheless you should note that when you use virtual inheritance you should call the constructor of the common base manually.
A derived object, by definition, is a base object as well.
A Derived
object should always be able to be used in place of a Base
object. If Base
has private members that need to be properly initialized for Base
to work, that is probably done in the constructor, so the Base
constructor should always be called.
精彩评论