Sobes.tech
Junior — Middle

Kas teil on kogemusi virtuaalsete destruktorite kasutamisel oma projektides?

sobes.tech AI

Vastus AI-lt

Virtual destructors in C++ are used for proper resource deallocation when objects are deleted through a pointer to the base class. If the class has virtual functions and inheritance is expected, the destructor should be virtual so that when delete is called through the base pointer, the destructor of the derived class 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 have used virtual destructors for correct memory and resource management in class hierarchies to prevent leaks and undefined behavior.