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

static data members

Started by sipickles Mar 19, 2005 at 6:23 AM 6 replies 1.3k views
Original Post
sipickles
sipickles
Hi, I am trying to find a way to store a common variable across several instances of the same class (rather than rely on a global variable). I thought that declaring it as a static data member, might work, but this seems complicated. Is there a simple way? I am using MSVC6
Shadx
Shadx
Depending on exactly what you are trying to do, static would certainly seems to be a good choice to achieving that goal. If you find this complicated, then any other way might look even more complicated.

So let say this common variable really belongs on that class and it's an int. In the header file you just declare it static.



static private int m_iStaticType.


and in the cpp file, you initialize it, otherwise it will give you a linker error

int MyClass::m_iStaticType = 0;

Pretty easy stuff :)

Cheers,

Shadx
kuphryn
kuphryn
In this case, static is sufficient.

Kuphryn
sipickles
sipickles
Would the int MyClass::m_iStaticType = 0; go in the cpp of the class or the app?
nilkn
nilkn
Quote:
Original post by sipickles
Would the int MyClass::m_iStaticType = 0; go in the cpp of the class or the app?


The .cpp file for the class.
Inmate2993
Inmate2993
/* THING.H file */#ifndef THING_H#define THING_Hclass Thing{  public:    Thing();    ~Thing();    static int GetRefCount();  private:    static int m_refcount;};#endif

-
/* THING.CPP file */#include "thing.h"int Thing::m_refcount = 0;Thing::Thing(){  m_refcount += 1;}Thing::~Thing(){  m_refcount -= 1;}int Thing::GetRefCount(){  return m_refcount;}


This is one of the best examples of how to do static class members.
william bubel
Qw3r7yU10p!
Qw3r7yU10p!
Quote:
Original post by Inmate2993

This is one of the best examples of how to do static class members.


Your code is counting the number of instances of the class rather than the number of references to a particular instance. The name of the variable is a bit misleading and certainly nothing to do with the usual idea of reference counting.
Inmate2993
Inmate2993
I guess my identifier is a bit vauge. Well, you'd have to do some operator overloading to do actual reference counting, which is beyond the scope of this thread.
william bubel

Topic Locked

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

Sign in to reply to this topic.