All Courses
OOP: CONSTRUCTORS AND DESTRUCTORS

Types of Destructors

A class has only one destructor, but we can discuss destructors by how they are provided or used.

1. Compiler-Generated Destructor

If you do not write a destructor, the compiler can generate one.

This is usually correct when all members clean themselves.

#include <string>
#include <vector>

class Student {
private:
    std::string name;
    std::vector<int> marks;
};

No custom destructor is needed here.

2. User-Defined Destructor

Write a destructor when your class directly owns a resource that must be released.

class IntArray {
private:
    int* data;

public:
    explicit IntArray(int size) : data(new int[size]) {}

    ~IntArray() {
        delete[] data;
    }
};

This example teaches cleanup, but modern C++ should usually prefer std::vector<int>.

3. Virtual Destructor

Use a virtual destructor in a base class that will be deleted through a base pointer.

#include <iostream>

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

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

int main() {
    Base* ptr = new Derived();
    delete ptr;
}

Output order:

Derived destroyed
Base destroyed

Why Virtual Destructor Matters

Without a virtual destructor, deleting a derived object through a base pointer may not destroy the derived part correctly.

This is a major polymorphism rule:

If a class has virtual functions and is meant to be used as a base class, give it a virtual destructor.

Viva Answer

There is only one destructor per class, but it may be compiler-generated, user-defined, or virtual. A virtual destructor is important for polymorphic base classes so derived objects are destroyed correctly through base pointers.

Quick Check

  • How many destructors can a class have?
  • When is the compiler-generated destructor enough?
  • When do you need a user-defined destructor?
  • Why should polymorphic base classes have virtual destructors?