[gameprogrammer] Re: Singleton

Hi,

> Regardless of whether Foo is a singleton or not, the compiler won't
> let me use foo_func from within Bar unless I have a FooPtr and use
> that to reference the function. I'm not proficient enough yet with C++
> to know if that's a language feature or just a compiler quirk (I
> suspect it's language), pointers are probably my weakest point so far.

This is because the compiler needs to know what object to perform the 
function on. Let's imagine how an object might look like in memory.

class IntObject {
        int value;
};

Now, instantiating this class will simply allocate sizeof(int) bytes to 
save the instance's data in. This is what a pointer to the instance 
points to.

Every member function (except static ones) takes a "this pointer" as an 
implicit first argument. That means that the function
        void IntObject::addWith(IntObject* other);
is actually translated to something like this:
        void IntObject_addWith(IntObject* this, IntObject* other);

This is of course because the function needs to know where to get the 
"value" member of the instance that addWith() is performed on.

Now for the relation with singletons:
Since a singleton class normally has an instance() method (or named 
similarly), this gives you (and the compiler) a this pointer to work 
with when using member functions. So you can write this line of code:

        TextureManager::instance()->loadTexture("SomeFilename");

assuming your TextureManager implements the loadTexture() function.

Now this looks pretty clumsy in C++, but one can't really help it. :(

HTH
- Sebastian


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


Other related posts: