Defining Macros that are equal to functions that return objects in C++

187 views Asked by At

So I have the singleton pattern working the way I want to, I think the main problem is something with pointers and refrences. ("..." represents irrelevent code).

Universe.h

...    
#define TheUniverse Universe::GetInstance ();
...
public:
static Universe& GetInstance ();
...
private:
static Universe* x_instance;
...

Universe.cpp

...
Universe* Universe::x_instance = NULL;
...
    Universe& Universe::GetInstance ()
{
    if ( x_instance == NULL )
    {
        x_instance = new Universe ();
    }
    return *x_instance;
}
...

Main.cpp

...
//This Works
Universe& universe = TheUniverse;

universe.Initialize();

//This also Works
Universe::GetInstance().Initialize();
//This Does Not (and I do not know why)
TheUniverse.Initialize();
//CMake says "error: expected primary-expression before '.' token TheUniverse.Initizlize();"

So, why do I have to set TheUniverse macro to a variable before I can use it? And is there a way for me to bypass this and not have to use a variable?

1

There are 1 answers

2
Nick Mertin On BEST ANSWER

The problem is that you defined TheUniverse as Universe::GetInstance();, with a semicolon. Therefore, after macros are processed, you get Universe::GetInstance();.Initialize(); which is obviously not what you want. To fix the problem simply remove the semicolon in the macro definition.