Why doesn't my short singleton code in c++ compile? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Why doesn't my short singleton code in c++ compile?

I know the code at https://www.tutorialspoint.com/Explain-Cplusplus-Singleton-design-pattern compiles and works but I want to write something shorter. The following gives me this compilation error. ../Playground/: /tmp/ccwamx3r.o: in function `main': file0.cpp:(.text+0x14): undefined reference to `Example::singleton' collect2: error: ld returned 1 exit status Why is "Example::singleton" undefined in main here? #include <iostream> using namespace std; class Example { public: int getValue(); static Example singleton; }; int Example::getValue() { return 1; } int main() { cout << Example::singleton.getValue() << endl; return 0; }

2nd May 2021, 4:46 PM
Josh Greig
Josh Greig - avatar
3 Answers
+ 8
You are only 'declaring' the static member 'singleton'. You are not initializing it (in fact, in C++ you cannot initialize static members from inside the class unless they're declared constexpr). That is why the compilation succeeds because the compiler knows that Example::singleton exists. But the linker fails because it does not know where Example::singleton is. You need to initialize Example::singleton from outside the class. Adding this line anywhere outside the 'Example' class will do it `Example Example::singleton;`
2nd May 2021, 5:05 PM
XXX
XXX - avatar
+ 5
Thanks, XXX. That works. Here is the working code: #include <iostream> using namespace std; class Example { public: int getValue(); static Example singleton; }; Example Example::singleton; int Example::getValue() { return 1; } int main() { cout << Example::singleton.getValue() << endl; return 0; }
2nd May 2021, 5:25 PM
Josh Greig
Josh Greig - avatar
+ 3
XXX Nice explanation. Josh Greig It's been over 2 decades since I spent much time with C++. Seeing this example has me wondering how a static types in C# are actually implemented when compiled to IL. Perhaps, it's not so different from how singletons are implemented in C++. It'll certainly be something I'll add to my short list of things to explore when I ever manage to find some free time. 😉
2nd May 2021, 6:13 PM
David Carroll
David Carroll - avatar