Home | | Computer Science 11th std | C++ Inheritance and constructors and destructors

Example Programs in C++ - C++ Inheritance and constructors and destructors | 11th Computer Science : Chapter 16 : Inheritance

Chapter: 11th Computer Science : Chapter 16 : Inheritance

C++ Inheritance and constructors and destructors

When an object of the derived class is created ,the compiler first call the base class constructor and then the constructor of the derived class.

Inheritance and constructors and destructors

 

When an object of the derived class is created ,the compiler first call the base class constructor and then the constructor of the derived class. This because the derived class is built up on the members of the base class. When the object of a derived class expires first the derived class destructor is invoked followed by the base class destructor.

 

Illustration 16.7 The order of constructors and destructors

#include<iostream>

using namespace std;

class base

{

public:

base()

{

cout<<"\nConstructor of base class...";

}

~base()

{

cout<<"\nDestructor of base class.... ";

}

};

class derived:public base

{

public :

derived()

{

cout << "\nConstructor of derived ...";

}

~derived()

{

cout << "\nDestructor of derived ...";

}

};

class derived1 :public derived

{

public :

derived1()

{

cout << "\nConstructor of derived1 ...";

}

~derived1()

{

cout << "\nDestructor of derived1 ...";

}

};

int main()

{

derived1 x;

return 0;

}

Output:

Constructor of base class...

Constructor of derived ...

Constructor of derived1 ...

Destructor of derived1 ...

Destructor of derived ...

Destructor of base class....

 

The constructors are executed in the order of inherited class i.e., from base constructor to derived. Thedestructors are executed in the reverse order.

 

Some Facts About the execution of constructor in inheritance

 

• Base class constructors are executed first ,before the derived class constructors execution

• Derived class can not inherit the base class constructor but it can call the base class constructor by using

• Base_class name::base_class_constructor() in derived class definition

• If there are multiple base classes ,then its start executing from the left most base class

• In multilevel inheritance, the constructors will be executed in the order of inheritance.

 

size of derived class object=size of all base class data members + size of all data members in derived class.

 

Tags : Example Programs in C++ , 11th Computer Science : Chapter 16 : Inheritance
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 16 : Inheritance : C++ Inheritance and constructors and destructors | Example Programs in C++


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.