Reputation: 51
#include <iostream>
using namespace std;
class MonsterDB
{
private:
~MonsterDB() {}; //private destructor
public:
static void DestroyInstance(MonsterDB* pInstance)
{
//static member can access private destructor
delete pInstance;
}
//...other methods
};
int main()
{
// instantiation in heap
MonsterDB* pMyDatabase = new MonsterDB();
MonsterDB::DestroyInstance(pMyDatabase);
return 0;
}
guys , why only static member can access private destructor?
When i remove static from this :
static void DestroyInstance(MonsterDB* pInstance)
i get an error!
The reason i asked the question is that :
#include <iostream>
using namespace std;
class MonsterDB
{
private:
int variable;
public:
void printer()
{
cout<<variable<<endl;
}
void instancer(int s)
{
variable = s;
}
//...other methods
};
int main()
{
MonsterDB obj1;
int var = 5;
obj1.instancer(var);
obj1.printer();
}
In the above code I made, both functions : printer and instancer accessed private variable without having to specify static keyword in those functions.
Sorry for your time, advance thanks! hoping to give real intuition behind this.
Upvotes: 0
Views: 70
Reputation: 1048
As you might recall, static
(in this context) means that the function behaves like a global function, meaning it is not bound to a single instance of the class.
MonsterDB::DestroyInstance(pMyDatabase);
Obviously, if DestroyInstance
is not static
, this line will always fail (and it has nothing to do with private destructors). Calling it like this
pMyDatabase->DestroyInstance(pMyDatabase);
will work even if the method is not static (although it is very awkward, it makes more sense to make this method static).
Upvotes: 1