Open In App

How to Restrict Dynamic Allocation of Objects in C++?

Last Updated : 21 Jun, 2022
Like Article

C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new. 
C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using the delete operator otherwise, a memory leak occurs. C++ doesn’t support the automatic garbage collection approach used by languages such as Java & C#. 
How do we achieve the following behavior from a class ‘Test’ in C++? 

Test* t = new Test; // should produce compile time error
Test t;    // OK 

The idea is to keep the new operator function private so that new cannot be called. See the following program. Objects of the ‘Test’ class cannot be created using new as new operator function is private in ‘Test’. If we uncomment the 2nd line of main(), the program would produce a compile-time error. 


// CPP Program to restrict dynamic
// allocation of objects in C++
#include <iostream>
using namespace std;
// Objects of Test can not be
// dynamically allocated
class Test {
    // new operator function is private
    void* operator new(size_t size);
    int x;
        x = 9;
        cout << "Constructor is called\n";
    void display() { cout << "x = " << x << "\n"; }
    ~Test() { cout << "Destructor is executed\n"; }
// Driver Code
int main()
    // Test* obj=new Test(); -> Uncommenting this line would
    // cause a compile time error.
    Test t; // Ok, object is allocated at compile time
    // object goes out of scope, destructor will be called
    return 0;


Constructor is called
x = 9
Destructor is executed

Also, it is a general query if we can allocate memory for the objects dynamically in C++? 

Yes, we can dynamically allocate objects also. 

  • Whenever a new object is created, constructor, a member function of a class is called.
  • Whenever the object goes out of scope, destructor, a class member function is called.

Time complexity : O(1) 
Auxiliary Space : O(1)

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads