How & When to Use C++’s Virtual Destructor?

Do destructors always get called for every object, or do we need to make them virtual? What is a virtual destructor anyway? We will try to answer these (and more) questions in this step by step guide to virtual destructors  and pure virtual destructors in C++.

What is a Virtual Destructor?

A destructor function is the inverse of a constructor function. Destructors are used when clean-up is necessary due to an object coming to an end since C++ does not have garbage collection like other languages such as Java. This destructor will call derived classes before the base class, whereas non-virtual destuctors will only delete base class objects.

What is a Pure Virtual Destructor?

Pure virtual destructors are used with abstract classes. Since every abstract class needs a pure virtual function, some programmers like to make the destructor pure virtual as a reminder that the class is abstract. In some cases, it is preferable to use pure virtual destructors rather than just a virtual one when no virtual calls are necessary.

How to Use a Virtual Destructor?

C++ uses ~ to define destructors. Making a destructor virtual is relatively simple. For example:

class MyBase
{
public:
MyBase()
{
printf(“\nConstructor\n”);
}
~virtual MyBase()
{
printf(“\nDestructor\n”);
}
};

Since C++ doesn’t have garbage collection, you need to manually delete all objects you created with new. For example:

MyClass::~class1(void)
{
delete object1;
delete object2;
}

Conclusion

When deleting an instance of an object, if we delete it through a base pointer without virtual destructors, the base class destructor will be called, which can cause memory leaks. Some programmers argue that if a class has any virtual function, it needs a virtual destructor, but here is a better rule of thumb. According to Sutter,”A base class destructor should be either public and virtual, or protected and nonvirtual.”

Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.