Build binary tree from ancestor matrics
February 2, 2013
Disallowing object creation on heap
February 5, 2013

Allowing only dynamic object creation on heap

Write a class, such that user can create its object on heap (using new) but user should not be able to create its object on stack or data area. i.e if the class is MyClass, then

MyClass stackObj;     // Should give compile time error.
MyClass *heapobj = new MyClass;      // This should be OK, & allowed.

Give the definition of class, MyClass (How should you change the scope or anything else of constructor / destructor / assignment operator or any other function, etc.).

Solution:

If destructor of a class is declared as private inside the class, then user will not be able to create object of that class on stack.

class MyClass
{
    private:
        ~MyClass(){}
};
int main()
{
    MyClass obj; // ERROR
}

In the main function, when we try to create object of MyClass, obj will get created, but when the control will move out of main function, compiler will attempt to call the destructor. Since the destructor is declared private, it is not possible to call it from outside the class scope, Hence error. This error is a compile-time error, So, the above program will not even compile.

The problem with our class definition is that it will not even allow the object creation on heap.

MyClass * ptr = new MyClass; // OK, because constructor (default) can be called from outside
delete ptr; // ERROR, for the same reason as above.

So we are not able to delete the object (if we don’t delete, it will leave memory leaks, if we try to delete it will give compile-time error).

We can overcome this problem by allowing alternate way to the user to delete the object on heap. Lets define another public function, which will call the delete function, as shown below.

class MyClass
{
    public:
        deleteObj(){ delete this; } // Call this to delete object on heap.
    private:
        ~MyClass(){}
};

Now, For heap objects, we can delete it manually, as shown below:

MyClass * ptr = new MyClass; // OK, because constructor (default) can be called from outside
ptr->deleteObj; // OK. Will delete the memory allocated to ptr.
ptr = NULL;

But compiler calls the destructor directly, which is not possible, hence no object of this class can be created on Stack or in data area.

Leave a Reply

Your email address will not be published. Required fields are marked *