Skip to content
Related Articles

Related Articles

Improve Article

C++ | Virtual Functions | Question 9

  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2021

Can a destructor be virtual?

Will the following program compile?

#include <iostream>
using namespace std;
class Base {
  virtual ~Base() {}   
int main() {
   return 0;

(A) Yes
(B) No

Answer: (A)

Explanation: A destructor can be virtual. We may want to call appropriate destructor when a base class pointer points to a derived class object and we delete the object. If destructor is not virtual, then only the base class destructor may be called. For example, consider the following program.

// Not good code as destructor is not virtual
using namespace std;

class Base  {
    Base()    { cout << "Constructor: Base" << endl; }
    ~Base()   { cout << "Destructor : Base" << endl; }

class Derived: public Base {
    Derived()   { cout << "Constructor: Derived" << endl; }
    ~Derived()   { cout << "Destructor : Derived" << endl; }

int main()  {
    Base *Var = new Derived();
    delete Var;
    return 0;

Output on GCC:
Constructor: Base
Constructor: Derived
Destructor : Base

Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :