I want to implement class with singleton pattern and have the instance of the class call the private member function.
#include <iostream>
using namespace std;
class Test {
private:
Test(){}
static Test* getInstance()
{
static Test obj;
return &obj;
}
public:
void print()
{
cout<<"test function"<<endl;
}
};
int main(int argc, const char * argv[]) {
Test::getInstance()->print(); //error!
return 0;
}
and I get error message form xcode
'print' is a private member of 'Test'
I think static instance can also call the private member function.
Apologies, I wrote the wrong code here. getInstance()
must be public as shown below:
#include <iostream>
using namespace std;
class Test {
private:
Test(){}
void print()
{
cout<<"test function"<<endl;
}
public:
static Test* getInstance()
{
static Test obj;
return &obj;
}
};
int main(int argc, const char * argv[]) {
Test::getInstance()->print();
return 0;
}
The above corrected code is the actual code.
Test::getInstance()
, which is a private member function. And hence cannot be accessed outside the class-scope. - WhiZTiMmain.cpp:23:23: error: 'static Test* Test::getInstance()' is private within this context
- qxzprint()
. - Justin Time - Reinstate Monica