Monday, January 17, 2011

Constructor Chaining

Constructor Chaining
You can achieve constructor chaining through inheritance. Constructor chaining is a process in which the first task of derived constructor is to call its base class constructor. There can be a number of classes in an inheritance chain. In constructor chaining the derive class will call its base class and this process will continue until it reaches its top most class and then all constructor will execute as a chain from top till original class.

Example
Let make a program to understand the mechanism of constructor chaining.


We have create three class. Stud, Male and Human. Stud is inherited from Male and Male is inherited from Human. Human is at the top and Stud is in bottom.



We have create an object of Stud class. What will happen if we create Stud object. Compiler will go to Stud constructor and before executing the Stud constructor it will go to its base class  (i.e. Male). Before executing Male constructor it will go to its base class (i.e.Human). Now complier have reached at the top and will start executing base constructor (i.e Human) then its (Human) derived class constructor (i.e. Male) then its (Male) derived class constructor (i.e Stud).


No comments:

Post a Comment