Order of Constructor Call in Inheritance

Order of Constructor Call in Inheritance

In inheritance we derive a class from the base class. Once inheritance takes place then we can create objects of the derived class. It is worth mentioning that objects of the derived class can access all the members of derived as well as base class.

While creating the object of the derived class, data members of both derived and base class need to be initialized. For this initialization of data members we use constructors.

Default Constructors of Base and Derived Classes

As the object of derived class use the data members of both derived and base class, therefore constructors of both derived and base class will be called while creating the object of derived class to initialize the corresponding data members.

 By default, the default constructor of base class is called unless specified explicitly.

The following example shows that if the object of derived class is created using the default constructor of derived class then it calls the default constructor of base class as well.

default constructor

roll number

We can see that while creating object of class Student at line 27, no parameters are passed. It means that the default constructor of Student class will be called which in turn will call the default constructor of base class Person. As a result the following output is produced.

result

Parameterized Constructors of Base and Derived Classes

If we want to mention the values to be assigned to the members of the object at the time of object creation then we will need to use the parameterized constructor of derived class which in turn calls the default constructor of base class but may call the specified parameterized constructor of base class as well if mentioned.

 The following code shows that how to mention that which constructor of base class will be called by the constructor of derived class at the time of object creation.

object creation

students

We can see at line 29 above that when the parameterized constructor of Student class is called, it in turn calls the parameterized constructor of Person class sending the values of name and age to the base class. The output of the above code is as below.

output

More Related Articles For You

    C++ Tutorial

    C++ Quizzes