I came across code like the below, which is basically an example of a singleton class in which we make the class constructor private and provide one static public function to create an instance of the class when required.
My question is when we call the new
operator to create an object of the singleton class inside the static function, then the constructor of the class will surely be called. I am confused how it happens because, as far I know, a static function can only access static members and static functions of a class. How then can it access a private function (the constructor) of a class?
Can a static function call any private or public member function of class without creating any instance?
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton(){}
static Singleton* instance;
};
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(!instance) {
instance = new Singleton(); //private ctor will be called
cout << "getInstance(): First instance\n";
return instance;
}
else {
cout << "getInstance(): previous instance\n";
return instance;
}
}
int main()
{
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
return 0;
}
But when I wrote a sample code as below:
class Sample
{
private:
void testFunc()
{
std::cout << "Inside private function" <<std::endl;
}
public:
static void statFunc()
{
std::cout << "Inside static function" <<std::endl;
testFunc();
}
};
int main()
{
Sample::statFunc();
return 0;
}
I get a compilation error with g++ :
file.cpp: In static member function ‘static void Sample::statFunc()’:
file.cpp:61: error: cannot call member function ‘void Sample::testFunc()’ without object.
If we can access private function of class with static public function then why i am getting this error?
getInstance
is a member of theSingleton
class, therefore it can call all methods of the class, even private ones. – Jabberwocky