Virtual Destructors in C++
Virtual destructors are used to release the memory occupied by the parent as well as child class object. If normal destructors are used then the obtained behavior may be different than the required one.
To understand the behavior of virtual destructors, let us have a look on the following code and its out.
At line number 25 a pointer object of Person class refers to the object of its child Student class. At line 26 the destructor is called. The intention to call the destructor here is to call the destructor of Student class but it never happens and the output of the above code is as below which shows that the destructor of Person class is called instead of Student class.
In order to call the destructor of child as well as parent class, we need to declare the destructors defined in parent class as virtual as shown in the following code.
As we can see at line 8, the destructor is declared as virtual. This will allow to call the destructors of both parent and child classes as shown in the figure below.
More Related Articles For You
- What is C++
- C++ and Object Oriented Programming OOPS concepts
- Syntax and Structure of C++ program
- Data Types in C++
- C++ Variables
- Types of operators in C++
- Decision making in C++
- C++ Loop Types
- Storage Classes in C++
- Functions in C++
- Classes and Objects in C++
- Access controls in C++ Classes
- Defining Class and Object in C++
- Accessing Public and Private Data Members in C++
- Member Functions in Classes
- Types of Member Functions in C++
- Inline Functions in C++
- Namespaces in C++
- Function Overloading in Classes in C++
- Constructors and Destructors in C++
- Static Keywords in C++
- Const Keyword in C++ Programming
- References in C++
- Copy Constructor in C++
- Pointer to Members in C++ Classes
- Introduction to Inheritance
- Types of Inheritance
- Order of Constructor Call in Inheritance
- Upcasting in C++
- Function Overriding in C++
- Virtual Functions in C++
- Abstract Class and Pure Virtual Functions in C++
- Operator Overloading in C++