Restriction on creation of object into heap, stack, static memory

asadullah.ansari's Avatar author of Restriction on creation of object into heap, stack, static memory
This is an article on Restriction on creation of object into heap, stack, static memory in C++.
Rated 5.00 By 3 users
This is just for a kind of information.

Here I am going to explain how to make a class so that user can create object
of it on free List( heap memory) or Stack.

Example 1: 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.
Code: Cpp
class HeapOnly
{
 public:
 void DestroyMe() //This function will call destructor
 {
   delete this;   // Current object will be deleted means destructor
 }
 private:
 ~HeapOnly();     // destructor only can be call by member function
};
Now you can test above class.
Code: Cpp
int main()
{
 HeapOnly
 HeapOnly * ptr = new HeapOnly;  // Object created on heap
 ptr->DestroyMe()                // Object deallocated
}
Example 2: Object should be created Only On stack memory or static memory. Idea
is that just overload the new and delete operator and make it private member
and dummy implemetation.

Code: Cpp
class autoOnly
{
  public:
    autoOnly()
    {
    ;
    }
    ~autoOnly()
    {
    ;
    }
  private:
    void* operator new(size_t)
    {
      // Dummy Implementation
    }
    void* operator new[](size_t)
    {
      // Dummy Implementation
    }
    void operator delete(void*)
    {
       // Dummy Implementation
    }
    void operator delete[](void*)
    {
      //Dummy Implementation
    }
};
Now you can test it .
Code: Cpp
int main()
{
  autoOnly *ptr= new autoOnly; // Error " cannt Access private member
  autoOnly obj;  // Created on stack
  static autoOnly obj1;  //Created on static memory
  return 0;
}
0
rashida.par's Avatar, Join Date: Feb 2008
Go4Expert Member
its a nice one i tried and god a lot of help
0
heena.mca's Avatar, Join Date: Feb 2008
Go4Expert Member
good one
0
rajkumar_singhalmca's Avatar, Join Date: Aug 2007
Light Poster
here u will knoew that how to will create that the object
but in mode the privat member function how to will create object and how to will access them.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination for article of the month of March
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Vote here - Voting for article of the month for Mar 2008