Define a class, for that only dynamic instance is possible. i.e object can be created on heap only.
Code:#include <iostream> using namespace std; /* Object should be created Only On Heap memory.Idea is that make constructor as private so that no one create on stack. But one drawback is that constructor can be overloaded so better make destructor as private member of class because Destructor can'nt be overloaded. It's very safe to make destructor as private member of class for this purpose. */ class HeapOnly { public: void DestroyMe() //This function will call destructor { delete this; // Current object will be deleted means destructor } void* operator new(size_t) { cout<<"Operator new"<<endl; } HeapOnly() { cout<<"Constructor"<<endl; } private: ~HeapOnly() { // destructor only can be call by member function cout<<"Deleting using private Destructor"<<endl; } }; int main() { // HeapOnly p; HeapOnly * ptr = new HeapOnly(); // Object created on heap ptr->DestroyMe(); // Object deallocated }
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks