Sobes.tech
Middle+

How to prevent a class user from creating an object of this class on the heap?

sobes.tech AI

Answer from AI

Declare the destructor as private.

class MyClass {
private:
    ~MyClass() {
        // Destructor code
    }

    // Other class members
public:
    // Constructors
    MyClass() {
        // Constructor code
    }

    // Other methods
};

// In code where we try to create an object on the heap:
// MyClass* obj = new MyClass(); // Compilation error: access to private destructor

// Creating an object on the stack is allowed:
// MyClass obj;

The user will only be able to create objects of this class on the stack, because the compiler explicitly calls the destructor to free memory when leaving the scope. But when trying to create an object on the heap using new, the compiler generates code for a subsequent call to delete, which requires access to the destructor. Due to the private access, calling delete becomes impossible, resulting in a compilation error.