Wednesday, 3 December 2014

How is it possible to restrict dynamic allocation of objects in C++?

How is it possible to restrict dynamic allocation of objects in C++?

Yes, it is possible only when we implement the new operator function in the private section.
See the below example
  #include <iostream>
using namespace std;
class MyTestClass
{
private:
    void* operator new(size_t size);
    int iVal;
public:
    MyTestClass ()          { iVal = 100; cout << "Constructor of the class is called\n"; }
    void display ()  { cout << "value is  = " << iVal << "\n";  }
    ~MyTestClass ()         { cout << "Destructor of the class is called\n"; }
};
int main()
{
 //  MyTestClass *ptr = new MyTestClass;
    MyTestClass ocTestCls;     
    ocTestCls.display();
    return 0;
} 




 When we try to create the object using new. The below error will appear. Because Objects of ‘MyTestClass’ class cannot be created using new as new operator function is private in ‘MyTestClass.


See the below output:

Constructor of the class is called

value is = 100


As we know, C++ supports stack allocated objects for the reason of runtime efficiency. Stack based objects are implicitly managed by C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using delete operator otherwise, memory leak occurs.

No comments: