[gameprogrammer] Re: Singleton (was: calling class member from another class)


Justin Coleman wrote:
> On Sun, 17 Oct 2004 10:23:01 -0300, Kevin Fields
> <drunkendruid@xxxxxxxxxxx> wrote:
> 
>>Correct me if I'm wrong, but, would you need to put a pointer to it anywhere
>>if it's a singleton?
>>Doesn't a singleton operate in global space, allowing you to call its
>>functions from anywhere?
>>The texture manager that I made for one of my games was a singleton, and I
>>didn't need to store a pointer to it anywhere. If I needed the manager, I
>>just included the header file to it and started using it right off the bat.
>>
>>Kevin
>>
> 
> 
> That's what I thought too, but MSVC.net wouldn't let me do it.
> Singleton or not, I had to have an instance of it already constructed
> in order to call a function. The compiler wouldn't let me put a
> function call to it inside another class without having the pointer,
> for some reason.

Generally, a singleton class needs to have an instance() method which 
returns a pointer to the (only) instance. In C++, this would have to be 
a static member function, something like this:

// Singleton.h
class Singleton {
public:
        Singleton() {}

        static Singleton* instance() {
                if(!myInstance) {
                        myInstance = new Singleton;
                }
                return myInstance;
        }
private:
        static Singleton* myInstance;
};

You'd also need to define the instance in some source file.

// main.cpp
#include "Singleton.h"
Singleton* Singleton::myInstance = 0;

I hope I got it right; haven't written a lot of C++ for a while now.

Sebastian


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: