Classes can have Constructors and/or Destructors and Derived Classes are no different.
Situation remains understandable until both the base and its derived class have Constructors and/or Destructors. Since the derived class contains more than one Constructors and/or Destructors, it becomes confusing which one will be called when.
This is because when an object the inherited class is constructed both the constructors (base’s and its own) should be invoked and same applies when it gets destructed.
This article will clear all this!
Consider the following example program:
// -- INHERITANCE --
// Constructors, Destructors
// and Inheritance
#include<iostream.h>
// base class
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
class derived:public base
{
public:
derived(){cout<<"Constructing Derived\n";}
~derived(){cout<<"Destructing Derived\n";}
};
void main(void)
{
derived obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived
Destructing Derived
Destructing Base
Press any key to continue
So here is the general rule:
Constructors are called in the order of derivation and Destructors in the reverse order.
One more example will clear the confusions, if any.:
// -- INHERITANCE --
// Constructors, Destructors
// and Inheritance
#include<iostream.h>
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
Press any key to continue
Related Articles: