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 safeto 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.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
};
Client Code:
int main(){
HeapOnly
HeapOnly * ptr = new HeapOnly; // Object created on heap
ptr->DestroyMe() // Object deallocated
}
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 .
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 .
Client Code:
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;
}
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;
}
2 comments:
Ni9ce concept Of private destructor.
Very cool stuff. i got it very nicley
Post a Comment