#include <iostream>
using namespace std;
class MonsterDB
{
private:
~MonsterDB() {}; // private destructor prevents instances on stack
public:
static void DestroyInstance(MonsterDB* pInstance)
{
delete pInstance; // member can invoke private destructor
}
void DoSomething() {} // sample empty member method
};
int main()
{
MonsterDB* myDB = new MonsterDB(); // on heap
myDB->DoSomething();
// uncomment next line to see compile failure
// delete myDB; // private destructor cannot be invoked
// use static member to release memory
MonsterDB::DestroyInstance(myDB);
return 0;
}
Here MonsterDB
is a class that prohibits Instantiation the stack. So the way to implement is to hide the destructor. So he created a method to clear the variable on heap. I understood till here. But why did he choose to make the method static
? Even if it not, we can still access the method. Am I correct? Also can someone point me to what is the use of static method? (I understood the use of static member, that is uniformity across all the instances, also that only static method can access static members).