Make C++ class whose object can only be dynamically created

The problem is to create a class such that the non-dynamic allocation of object causes compiler error.
For example, create a class ‘Test’ with following rules.Test t1; // Should generate compiler error

Test *t3 = new Test; // Should work fineSolution:-The idea is to create aprivate destructorin the class. When we make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use.Since compiler is not responsible for deallocation of dynamically allocated objects (programmer should explicitly deallocate them), compiler won’t have any problem with them.
To avoid memory leak, we create a friend function destructTest() which can be called by users of class to destroy objects.// A class whose object can only be dynamically created

class Test
{
private:
~Test() { cout << “Destroying Objectn”; }
public:
Test() { cout << “Object Createdn”; }
friend void destructTest(Test* );
};

// Only this function can destruct objects of Test

void destructTest(Test* ptr)
{
delete ptr;
cout << “Object Destroyedn”;
}

int main()
{
///* Uncommenting following following line would cause compiler error */
// Test t1;
// create an object

Test *ptr = new Test;
// destruct the object to avoid memory leak
destructTest(ptr);

return 0;
}Output:Object Created
Destroying Object
Object Destroyed

News Reporter

Leave a Reply

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