Nicolas Nicolas - 1 month ago 6
C++ Question

How to make a C++ class whose objects can only be dynamically allocated?

The problem is to create a class such that the non-dynamic allocation of object causes compiler error.

For example :

Employee e1; // compiler error
Employee *e3 = new Employee; // works fine

Answer

Create a private destructor in the class. When you make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use.