Undefined reference? Is there something I'm not seeing? (c++, singleton class)
Question
I can't seem to make this undefined reference go away.
I have this code under the private section of Scene.h:
static Scene * scene_;
There is a #include "Scene.h" at the very first part of the header of Scene.cpp
This is the only error I'm receiving at the moment, any ideas?
I'll supply any other info you want.
Solution
When you declare a static member you must also define it in one compilation unit (and only one):
// a.h
class A
{
static int x;
};
// a.cpp
int A::x = 0;
The declaration of the variable in the class will not reserve memory, just tell the compiler (from other compilation units) that there will be a variable accessible by that name defined somewhere.
OTHER TIPS
Why use a Scene*
instead of a Scene
? You're essentially saying "use static
to allocate enough space for a pointer to a Scene
" and then at run time you put that Scene
object on the heap with new
(and, I assume, never delete
it).
Instead, just have static allocate and initialize the Scene
object:
static Scene scene_;
and then change all references to scene accordingly (-> becomes .):
scene_.addObject(&object);
This is easier and takes fewer keystrokes to boot. C++ doesn't require new
as often as Java or C#.