Constructor In Inheritance
With reference to inheritance, one important point to learn is how the constructors behave during the inheritance process.
When a child class inherits from a base class and base class has a constructor, it will always run first when the object of the child class in declared. If the child class too has a constructor it will always run after the base class constructor. In a nutshell "The order of constructor invocation in inheritance will be base class followed by the child class". In multiple inheritance where a child class is derives its behaviour from more than one classes, the order of invocation will be the same as order of inheritance.
For example, in the syntax
class child : public base1,public base2
the constructor of "base1" will be processed first followed by the "base2" constructor. The constructor of the "child" class will always be the last one to processed.
Constructor in Single Inheritance
Consider the following code snippet
class base
{
public:
base()
{
cout<<"\nBase Class Constructor";
}
}
{
public:
base()
{
cout<<"\nBase Class Constructor";
}
}
class derived : public base
{
public:
derived() {
cout<<"\nDerived Class Constructor";
}
}
{
public:
derived() {
cout<<"\nDerived Class Constructor";
}
}
When the above code is compiled the output shown will be
Base Class Constructor
Derived Class Constructor
Here’s what actually happens when the base is instantiated:
- Memory for Base is set aside
- The appropriate Base constructor is called
- The initialization list initializes variables
- The body of the constructor executes
- Control is returned to the caller
Here’s what actually happens when Derived is instantiated:
- Memory for Derived is set aside (enough for both the Base and Derived portions).
- The appropriate Derived constructor is called
- The Base object is constructed first using the appropriate Base constructor
- The initialization list initializes variables
- The body of the constructor executes
- Control is returned to the caller
The only real difference between this case and the non-inherited case is that before the Derived constructor can do anything substantial, the Base constructor is called first. The Base constructor sets up the Base portion of the object, control is returned to the Derived constructor, and the Derived constructor is allowed to finish up it’s job.
0 comments:
Post a Comment