+ Reply to Thread
Results 1 to 2 of 2

Thread: heap only instance of a class

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    heap only instance of a class

    Define a class, for that only dynamic instance is possible. i.e object can be created on heap only.

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    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
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts