- 2072 Chaitra · 4 marks
Virtual destructor with example
Short answer
If a derived object is deleted through a base pointer without a virtual destructor, only the base destructor runs, laking resources. A virtual destructor ensures the derived destructor executes first, then the base's, preventing memory leaks. Example: virtual ~Base(){}.
Why do you need Virtual Destructor? Explain with example.
A virtual destructor is a destructor declared with the keyword virtual in the base class.
Need
When a derived class object is deleted through a base class pointer, and the base destructor is not virtual, only the base destructor is called. The derived destructor is skipped, so resources acquired by the derived class (memory, files) are never released, causing a memory leak and undefined behaviour. Making the base destructor virtual ensures the derived destructor runs first, then the base destructor, in the correct order.
Without virtual destructor
#include <iostream>
using namespace std;
class Base {
public:
~Base() { cout << "Base destructor" << endl; }
};
class Derived : public Base {
int *p;
public:
Derived() { p = new int[100]; }
~Derived() { delete[] p; cout << "Derived destructor" << endl; }
};
int main() {
Base *b = new Derived;
delete b; // only Base destructor runs: memory leak
return 0;
}
Output: Base destructor
With virtual destructor
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() { cout << "Base destructor" << endl; }
};
class Derived : public Base {
int *p;
public:
Derived() { p = new int[100]; }
~Derived() { delete[] p; cout << "Derived destructor" << endl; }
};
int main() {
Base *b = new Derived;
delete b; // both destructors run
return 0;
}
Output:
Derived destructor
Base destructor
Rule: any class meant to be used as a base class with virtual functions should have a virtual destructor. Constructors cannot be virtual.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Need of virtual function · Object Oriented Programming, chapter 7 · asked 4×
- Need of virtual base class · Object Oriented Programming, chapter 6
- Virtual short circuit and inverting integrator · Basic Electronics Engineering, chapter 4
- Virtual memory management; thrashing · Operating System, chapter 4
- Human need and Herzberg's hygiene theory · Organization and Management, chapter 8 · asked 2×
- Election algorithm need and example · Distributed System, chapter 6 · asked 2×