Constructors are used to initialized data members in an object and also for allocating memory for the objects. In the case of inheritance, the objects of the derived class are usually used instead of the base class objects. Hence objects of the derived class are initialized using constructors and if there is a need , the base class objects are also initialized using derived class constructors

when a base class and a derived class both have constructors ans destructor functions, the constructor functions are executed in the order of derivation. That is , the base class constructor is executed before the constructor in  the derived class.

The destructor functions are executed in the reverse order. That is, the derived class destructor is executed before the base class destructor. Further arguments can be passed from the derived class constructor to the base class constructor.the syntax for passing arguments from derived class constructor is:

derived(arg-list):base(arg-list)
{
        //body of the derived class constructor
}

where, derived is the name of the derived class, base is the name of the  base class, and the argument lists in the two constructors can be same or different. when they are different, we must pass to the derived class constructor all arguments need by both the derived class and the base class. Then the derived class simply passes to the base class all those arguments required by it.

In the case of multiple inheritance, the constructors are executed i tneh order based classes are specified. Destructors are expected in the reverse order. The general syntax for derived class constructor in the case of multiple  inheritance is:
derived (arg-list): base 21(arg-list),base2(arg-list),...
{
// body of the derived class constructor
}
where, derived is the name of the derived class and base1,base2,.... are the names of the base classes. the argument list in the derived class constructor consists of all arguments needed by the derived class and all the base classes. 

// This program illustrates order of execution of constructors and destructors in the base class and the //derived class. Both the constructors use the same arguments.
#include<iostream>
using namespace std;
class base
{
int i;
public:
base(int n)
{
cout<<"Constructing base class\n";
i=n;
}
~base()
{
cout<<"Destructing base clas\n";
}
void show()
{
cout<<"i="<<i<<"\n";
}
};
class derived:public base
{
int j;
public:
derived(int n):base (n)
{
cout<<"Constructing derived class\n";
j=n;
}
~derived()
{
cout<<"Destructing derived class \n";
}
void showj()
{
cout<<"j="<<j<<"\n";
}
};
void main()
{
derived ob(10);
ob.showj();
ob.showj();
}

Result:

constructing base class
constructing derived class
i=10
j=10
destructing derived class
destructing base class
Posted by Unknown On 22:35 No comments

0 comments:

Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

Blog Archive

Contact Us


Name

E-mail *

Message *