C++ Derived Constructor and Destructor

October 27, 2015 Posted by WithU Technologies
As we already learn in the exceptions of Inheritance that Constructor and Destructor are not inherited from the base class.

But when the object of the Derived class is being created or deleted, the Constructor and Destructor of Base class can be called from the main function().

Example:

#include <iostream>
using namespace std;

// Base class

class Cars{

   public:

      Cars()   //Base Class Constructor declared and defined

      {

       cout<<"Base Class Constructor Called"<<endl;

      }

      ~Cars()  //Base Class Destructor declared and defined

      {

        cout<<"Base Class Destructor Called"<<endl;

      }

};

// Derived class

class Bolero: public Cars    //Bolero is Derived Class and Cars is the Base class

{

   public:

      Bolero()   //Derived Class Constructor declared and defined

            {

             cout<<"Derived Class Constructor Called"<<endl;

            }

   ~Bolero()    //Derived Class Destructor declared and defined

            {

              cout<<"Derived Class Destructor Called"<<endl;

            }

};

int main()   //main function

{

   Bolero b;  //Derived Class Bolero is called

   return 0;    //return void

 }

/* Output:

Base Class Constructor Called

Derived Class Constructor Called

Derived Class Destructor Called

Base Class Destructor Called

 */

·         We first create the Base class Cars with its own Constructor and Destructor. And then we also do the same for the derived class.

·         After compilation we get the output in particular sequence which we need to understand.

·         As we can see here that the Base Class Constructor is called first and then the derived class Constructor.

·         But after that the derived class destructor is displayed before the Base class Destructor.

·         And secret behind this sequence is that the Derived class needs its base class in order to work. That is why the base class is set up first and deleted last.