How to restrict dynamic allocation of objects in C++?


In this tutorial, we will be discussing a program to understand how to restrict dynamic allocation of objects in C++.

For this we will be keeping the new operator function private so that objects cannot be created using it dynamically.

Example

 Live Demo

#include <iostream>
using namespace std;
class Test{
   //making new operator private
   void* operator new(size_t size);
   int x;
   public:
   Test() { x = 9; cout << "Constructor is called\n"; }
   void display() { cout << "x = " << x << "\n"; }
   ~Test() { cout << "Destructor is executed\n"; }
};
int main(){
   Test t;
   t.display();
   return 0;
}

Output

Constructor is called
x = 9
Destructor is executed

Updated on: 02-Mar-2020

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements