Junior — Middle
Have you had experience using virtual destructors in your projects
sobes.tech AI
Answer from AI
Virtual destructors in C++ are used for proper resource cleanup when deleting objects through a pointer to the base class. If a class has virtual functions and inheritance is expected, the destructor should be virtual so that when delete is called through a base pointer, the derived class's destructor is invoked.
Example:
class Base {
public:
virtual ~Base() { std::cout << "Base destructor" << std::endl; }
};
class Derived : public Base {
public:
~Derived() override { std::cout << "Derived destructor" << std::endl; }
};
int main() {
Base* obj = new Derived();
delete obj; // calls Derived::~Derived() and then Base::~Base()
}
In my projects, I used virtual destructors for proper memory and resource management in class hierarchies to avoid leaks and undefined behavior.