Sobes.tech
Junior — Middle

Is it possible to create a new object inside a class destructor?

sobes.tech AI

Answer from AI

In a C++ class destructor, it is technically possible to create a new object, for example, by calling another object's constructor or allocating memory. However, this is highly discouraged and can lead to unpredictable behavior or memory leaks.

The destructor is intended to release the resources of the current object, not to create new ones. Creating objects inside a destructor can cause problems, for example, if the new object depends on resources that are already being destroyed.

An example of undesirable code:

class Example {
public:
    ~Example() {
        // Creating an object inside the destructor
        AnotherClass obj;
        // ...
    }
};

It is better to avoid such practices and create objects elsewhere in the program.