Jump to content
  • Advertisement


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


Private(?) Static class members

This topic is 6151 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
  // 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
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
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;

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


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

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!