Data Structures using C PlusPlus: Chapter 2: Inheritance and Polymorphism

Constructors and Destructors in Derived Classes

Data Structures using C++ Program

Questions: 1. Explain the order of execution of constructor and destructor with the help of suitable example. 2. Write a program to illustrate how constructors are implemented when the classes are inherited?

Constructors and Destructors in Derived Classes

 

• In the inheritance, First the Base class constructor is called, and after that the Derived class constructor is called. Because the Derived class inherits from the Base class, both the Base class and Derived class constructors will be called when a Derived class object is created.

• When the main function is finished running, the object's destructor will get called first, and after that the Base class destructor will be called.

• Following code illustrates this execution order

#include <iostream>

using namespace std;

class Base

{

public:

Base()

{

   cout << "Base constructor" << endl;

}

~Base()

{

   cout << "Base destructor" << endl;

}

};

class Derived:public Base

{

public:

Derived()

{

   cout<<"Derived constructor" << endl;

}

~Derived ()

{

   cout<<"Derived destructor" << endl;

}

};

void main()

{

   Derived obj;

}

Output

Base constructor

Derived constructor

Derived destructor

Base destructor


Review Questions

1. Explain the order of execution of constructor and destructor with the help of suitable example.

2. Write a program to illustrate how constructors are implemented when the classes are inherited?

 

Data Structures using C PlusPlus: Chapter 2: Inheritance and Polymorphism : Tag: Data Structure, C++, C Programing : Data Structures using C++ Program - Constructors and Destructors in Derived Classes


Data Structures using C PlusPlus: Chapter 2: Inheritance and Polymorphism



Under Subject


Data Structures using CPlusPlus

CS25C05 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Electron Devices

EC25C01 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Data Structures using CPlusPlus

CS25C05 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Circuits and Network Analysis

EC25C02 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Engineering Drawing - Laboratory

ME25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Data Structures using CPlusPlus - Laboratory

CS25C05 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Devices and Circuits Laboratory

EC25C03 2nd Semester ECE Dept | 2025 Regulation | 2nd Semester 2025 Regulation