What is the purpose of a virtual destructor in object-oriented programming?
sobes.tech AI
Answer from AI
A virtual destructor in object-oriented programming in C++ is used to properly release resources when deleting objects through a pointer to the base class.
If the base class has virtual functions, but the destructor is not declared virtual, then deleting a derived class object through a base class pointer will only call the base class destructor. This can lead to memory leaks or other errors, as the destructor of the derived class will not be called.
By declaring the destructor of the base class as virtual, we ensure that when deleting an object through a base class pointer, destructors of all hierarchy levels are called, starting from the derived class and ending with the base class.
Example:
class Base {
public:
virtual ~Base() { /* cleanup of base resources */ }
};
class Derived : public Base {
public:
~Derived() override { /* cleanup of Derived resources */ }
};
Base* obj = new Derived();
delete obj; // calls ~Derived() and then ~Base()
Without a virtual destructor in Base, only ~Base() would be called, which is incorrect.