Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Restriction on creation of object into heap, stack, static memory (http://www.go4expert.com/articles/restriction-creation-object-heap-stack-t9247/)

asadullah.ansari 11Mar2008 17:04

Restriction on creation of object into heap, stack, static memory
 
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;
}


rashida.par 13Mar2008 15:33

Re: Restriction on creation of object into heap, stack, static memory
 
its a nice one i tried and god a lot of help

heena.mca 13Mar2008 16:02

Re: Restriction on creation of object into heap, stack, static memory
 
good one

rajkumar_singhalmca 28Mar2008 14:31

hello
 
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.

shabbir 4Apr2008 18:45

Re: Restriction on creation of object into heap, stack, static memory
 
Nomination for article of the month of March

shabbir 17Apr2008 15:51

Re: Restriction on creation of object into heap, stack, static memory
 
Vote here - Voting for article of the month for Mar 2008


All times are GMT +5.5. The time now is 02:30.