Archived

This topic is now archived and is closed to further replies.

Zero-X

Private(?) Static class members

Recommended Posts

Zero-X    122
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

Share this post


Link to post
Share on other sites
Bad Monkey    145
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

Share this post


Link to post
Share on other sites
Dire.Wolf    122
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

Share this post


Link to post
Share on other sites