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?
static Singleton singletonis a declaration of something that is visible everywhere class is defined (e.g. in every source file that includes the header that defines the class) and must be defined exactly ones. Whereas, the same line in a function definition is a definition, that only exists within scope of that function (and that function can only be defined once).