Skip to main content
GameDev.net gamedev.net
🔒 Locked

Private(?) Static class members

Started by Zero-X Jan 9, 2002 at 11:06 PM 1 replies 550+ views
Original Post
Zero-X
Zero-X
I''m trying to read this source code, but I''m somewhat unfamiliar with some of the style/techniques used, due primarily to a chronic case of newbieness (on my part, obviously). My class definition for CMain contains
private:
  // Force the calling of a constructor, but because it is private, it cannot be allocated on the stack.
  // You must use "getInstance" to gain an instance
  CMain () {} ;
  static  CMain m_instance  
main.cpp contains this here little statement
// Our only instance of the CMain-class
CMain CMain::m_instance ; 
Am I to understand that this statement is declaring the static member m_instance to be a an object of the class CMain? You can set a static member''s value without an actual object by simply using the class name? Is it some sort of special exception that code outside of CMain''s functions is able to modify the value of CMain::m_instance despite it being private? Thanks in advance
Bad Monkey
Bad Monkey
This is a pattern known as a Singleton. You use this if you only want there to be one of a given type of object in existence at any time.

To "access" and change the state of the object, you must get a pointer/reference to it (via a static method, usually called "getInstance" or the like).

By declaring the object as a static member of the class, you can avoid having to allocate it on the heap (and hence avoid explicitly cleaning it up later)

This is a very useful design pattern, and I suggest you read up further on it... here's something to get you started

Hope that helped

Edited by - Bad Monkey on January 9, 2002 12:46:59 AM
Dire.Wolf
Dire.Wolf
More generally, static member functions of a class can be called without having an instance of the class.

To call a non-static member function you have to have an instance of the class:

ClassA a;
a.Method();

With a static member function you can use the classname and the scope resolution operator to directly access it:

ClassA::StaticMethod();


Static methods cannot access other, non-static member variables.

For instance:

class A
{
static void Test()
{
m_testme = 5; // ERROR: will not compile
m_testme2 = 10; // OK
}

int m_testme;
static int m_testme2;
};

Hope this helps.

Dire Wolf
www.digitalfiends.com
[email=direwolf@digitalfiends.com]Dire Wolf[/email]
www.digitalfiends.com

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.