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.
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