Sunday, August 30, 2015

How Derived classes are constructed in C++

Inheritance is one of the object oriented concept where one object inherits the behavior of another object. This concept is mainly used by the programmers for the purpose of reusing their code.

To know how the order of derived class works lets start with an example:

#include<iostream>
using namespace std;

class Base {
private:
 int base_var;
public:
 Base() {
  base_var = 10;
  cout << "Base is called \n";
 }
};
class Derived: public Base {
private:
 int derived_var;
public:
 Derived() {
  derived_var = 0;
  cout << "Derived is called \n";
 }
};

int main() {
 cout << "Instantiating Base class \n";
 Base b;
 cout << "Instantiating Derived class \n";
 Derived d;

 return 0;
}

In this example the Derived class is derived from Base class, Derived class inherits the public functions and public variables of base class. Figure 1 shows the diagrammatic representation of the classes.
 
                                                                    Figure 1


 If we run the above problem the output looks like this:

Instantiating Base class 
Base is called 
Instantiating Derived class 
Base is called 
Derived is called 

What can we conclude from the output? We can say that when we instantiate a derived class it first calls base part and then derived part. So derived portion consists of two parts: a Base part and a derived part.
When the compiler constructs the derived objects, it does in such a way that it starts with base. Once the base portion is complete it then walks through the inheritance tree and constructs the derived portion. So what actually happens in this example is that the Base portion of Derived is constructed first. Once the Base portion is finished, the Derived portion is constructed. At this point, there are no more derived classes, so we are done.

The construction of the derived classes always starts with base class and then the next derived class and then so on until we reach our actual derived class.


No comments:

Post a Comment