How do you prevent heap allocation in C++ for a Class?

(Last Updated On: May 6, 2017)

C++ Interview Question Description: Describe the concept to prevent heap allocation in C++ for a class i.e. object creation on heap. Means, dynamic memory allocation using new operator. Note that we don’t want to restrict object creation in stack in C++ class. So, explain how to prevent object creation on heap with a program example.

Answer:  let’s elaborate prevent heap allocation in C++  for a class question in a simple way.

If we have a class A, object creation of class A using new operator should not be allowed, but without using new operator it should be allowed. Below example show how to create object on heap and how to on stack.

 

 

Not that, since, we want to allow statement “A obj” i.e. object creation on stack, we cannot make the class constructor private.

To prevent dynamic memory allocation or just say to disallow heap allocation in c++ for class objects using “new” operator, we need to consider two things.

  1. First, overload the “new” operator in the class. So that, when we create object using “new”, it will not request memory from operating system but will call overloaded “new” method from the class itself for memory allocation.
  2. Make the overload new method private to make it in-accessible from outside of the class. As, we don’t want user to call “new”.

So, now, we can request memory neither from operating system nor from overloaded new operator from class. Now, we have only option for static memory allocation for this class objects.

Note that, we will be only be declaring overloaded new operator in C++ class but not defining it, as there is no use of it here, as we just want to make it in accessible form outside of class.

 

Example: