MCN Professionals | Interview Question of the day
MCN Professionals is starting Industrial Training for MCA-2012 Batch. Have a look at our Industrial Training Program and Course Details.
-----------------------------------------------------------------------------------------------------------------------------------------
Today's Question:
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. So it 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 the class (should you change the scope or anything else of constructor / destructor / assignment operator or any other function).
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. But since the destructor is declared private, it is not possible to call it from outside the class scope, Hence error.
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(){}
};
---------------------------------------------------------------------------
Interview Questions Archive:
To see all the questions in the category click
here...