Can a destructor be virtual in C++? Why or why not?

Yes, a destructor can be virtual in C++, and it should be virtual in a base class if you expect polymorphic behavior (i.e., if the class is meant to be inherited and deleted via a base class pointer).

Why?

If a base class destructor is not virtual, and you delete a derived class object through a base class pointer, only the base class destructor will be called, leading to a memory leak or undefined behavior.

Example (Without Virtual Destructor – Leads to Issue)

#include <iostream>

class Base {
public:
    ~Base() { std::cout << "Base Destructor\n"; }  // Not virtual
};

class Derived : public Base {
public:
    ~Derived() { std::cout << "Derived Destructor\n"; }
};

int main() {
    Base* obj = new Derived();
    delete obj;  // Only Base destructor is called, not Derived's
    return 0;
}

Output:

Base Destructor

👉 Problem: Derived destructor is never called, causing resource leaks if Derived has allocated memory.

Fix: Make Destructor Virtual

#include <iostream>

class Base {
public:
virtual ~Base() { std::cout << "Base Destructor\n"; } // Virtual
};

class Derived : public Base {
public:
~Derived() { std::cout << "Derived Destructor\n"; }
};

int main() {
Base* obj = new Derived();
delete obj; // Both destructors are called properly
return 0;
}

Ouput:

Derived Destructor
Base Destructor

Now it’s correct! Derived destructor runs first, followed by Base, ensuring proper cleanup.

Conclusion:

Always declare a virtual destructor in a base class meant for polymorphism.
❌ If the class is not meant to be used polymorphically (no virtual functions), a virtual destructor is unnecessary.