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.
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.
int main()
{
HeapOnly obj; //Error will come
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.
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 .
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;
}