Junior — Middle
What is the role of the keyword 'virtual' when declaring a destructor in the C++ programming language?
sobes.tech AI
Answer from AI
The virtual keyword when declaring a destructor in C++ guarantees that when an object is deleted through a pointer to the base class, the destructor of the derived class will be called. This is important for proper resource cleanup and preventing memory leaks.
If the base class destructor is not virtual and the object is deleted through a base class pointer, only the base class destructor will be called, not the derived class destructor.
Example:
class Base {
public:
virtual ~Base() { std::cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
~Derived() { std::cout << "Derived destructor\n"; }
};
int main() {
Base* obj = new Derived();
delete obj; // Will call Derived::~Derived(), then Base::~Base()
}