Code 1:
#include<iostream>
class Singleton
{
private:
static Singleton instance; //declaration of static variable
public:
static Singleton &GetInstance()
{
return instance;
}
void Hello()
{
std::cout << "Hello!";
}
};
Singleton Singleton::instance; //definition of static variable
int main()
{
Singleton::GetInstance().Hello();
}
Code 2:
#include <iostream>
class Singleton
{
public:
static Singleton &GetInstance()
{
static Singleton instance; //declaration of static variable
return instance;
}
void Hello()
{
std::cout << "Hello!";
}
};
int main()
{
Singleton::GetInstance().Hello();
}
In Code 1 we're required to define the static variable, but in Code 2, we just declared the static variable in the function Singleton::GetInstance&() and then returned it. Do the declaration and definition happen in the same line in Code 2? and why?