Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 691
Sadique Avatar asked Feb 28 '26 04:02

Sadique


2 Answers

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.

like image 135
Kirill V. Lyadvinsky Avatar answered Mar 01 '26 16:03

Kirill V. Lyadvinsky


A derived object, by definition, is a base object as well.

like image 29
Jerry Coffin Avatar answered Mar 01 '26 16:03

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!