Thursday 9 April 2015

Constructors in Inheritance

The constructors play an important role in initializing an object’s data members and allocating required resources such as memory. The derived class need not have a constructor as long as the base class has a no-argument constructor. However, if the base class has constructors with arguments then its is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. In the application of inheritance, objects of the derived class are usually created instead of the base class.

Hence, it makes sense for the derived class to have constructor and pass arguments to the constructor of the base class. When an object of a derived class is created, the constructor of the base class is executed first and later the constructor of the derived class.


In multiple inheritance, the constructors of base classes are invoked first, in the order in which they appear in the declaration of the derived class, whereas in the case of multilevel inheritance, they are executed in the order of inheritance.


It is responsibility of the derived class to supply initial values to the base class constructor, when the derived class objects are created. Initial values can be supplied either by the object of a derived class or a constant value can be mentioned in the definition of the constructor. The syntax for defining a constructor is

Derived_classname(argumentlist):base(argument),base(argument)….
{
body of derived class constructor
}

Constructors in Single Inheritance

Sample Program

#include <iostream.h>
class base
{
int a,b;
public:
base(int x, int y)
{
a = x;
b = y;
}
void showbase(void)
{
cout<<”Base value are”;
cout<<a<<b<<endl;
}
};
class deri:public base
{
int x,y;
public:
deri(int k, int l, int m, int n):base(m,n)
{
x = k;
y = l;
}
void showderi(void)
{
cout<<”derived values are”;
cout<<x<<y<<endl;
}
};
void main()
{
deri D(10,20,30,40);
D.showbase();
D.showderi();
}


No comments:

Post a Comment