Nicolas Nicolas - 1 year ago 82
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download