Thursday, 28 May 2015

Demonstration of Constructors and destructors in C++

Multilevel Inheritance is very useful to know how constructors and destructors work.
Below is the output of the code  have a look at it and you will get to know.


//illustration of how constructors and destructors work in c++
#include<iostream>
using namespace std;
class A
{
   public:
       A();
       ~A();
};
class B:public A
{
   public:
       B();
       ~B();
};
class C:public B
{
   public:
       C();
       ~C();
};
A::A()
{
   cout<<"\nthis is A constructor class\n";
}
A::~A()
{
   cout<<"\n this is A destructor class\n";
}
B::B()
{
   cout<<"\n this is B constructor\n";
}
B::~B()
{
   cout<<"\nthis is B destructor\n";
}
C::C()
{
   cout<<"\nthis is C constructor\n";
}
C::~C()
{
   cout<<"\nthis is C destructor\n";
}
int main()
{
   C objc;
 return 0;
}


First compiler goes to first parent class(A) displays its constructor then next child class(B) constructor 

then to the c class constructor.But the destructors goes in reverse manner of constructors as you see.

Hope this gave you a knowledge on constructors and destructors.Please comment below if you have 

any doubts regarding this












No comments:

Post a Comment