Can someone explain what I'm doing wrong?

The following simple snippet illustrates my problem. The linker gives the error "unresolved external symbol 'private: static int CStaticTest::m_Count' ". I'm using VC++ 6.

class CStaticTest
{
public:
CStaticTest();
~CStaticTest();
private:
static int m_Count;
};

CStaticTest::CStaticTest()
{
m_Count++;
}

CStaticTest::~CStaticTest()
{
m_Count--;
}

Re: static member variable access by GuitarBill

GuitarBill
Wed Jul 14 17:19:10 CDT 2004

You must instantiate the variable in the source - you have declared it but
not instantiated it.
eg in StaticTest.cpp

int CStaticTest::m_Count(0);

Some people like to distingush static members using 'sm' prefix (ie
sm_count).

Bill

"Roger" <Roger@discussions.microsoft.com> wrote in message
news:DBC32772-A597-4929-BF21-5CF3B12D954A@microsoft.com...
> Can someone explain what I'm doing wrong?
>
> The following simple snippet illustrates my problem. The linker gives the
error "unresolved external symbol 'private: static int CStaticTest::m_Count'
". I'm using VC++ 6.
>
> class CStaticTest
> {
> public:
> CStaticTest();
> ~CStaticTest();
> private:
> static int m_Count;
> };
>
> CStaticTest::CStaticTest()
> {
> m_Count++;
> }
>
> CStaticTest::~CStaticTest()
> {
> m_Count--;
> }



Re: static member variable access by Victor

Victor
Wed Jul 14 17:19:44 CDT 2004

Roger wrote:
> Can someone explain what I'm doing wrong?
>
> The following simple snippet illustrates my problem. The linker gives the error "unresolved external symbol 'private: static int CStaticTest::m_Count' ". I'm using VC++ 6.
>
> class CStaticTest
> {
> public:
> CStaticTest();
> ~CStaticTest();
> private:
> static int m_Count;
> };
>
> CStaticTest::CStaticTest()
> {
> m_Count++;
> }
>
> CStaticTest::~CStaticTest()
> {
> m_Count--;
> }

Every static data member of any class, if used outside the class,
has to be _defined_ at the namespace level (didn't tell you that
in the C++ book you're reading?)

You need to add this here (or anywhere in a C++ translation unit):

int CStaticTest::m_Count;

(make sure it's compiled only once, otherwise you're going to have
"multiple definition" error)

You forgot define a copy constructor and do the same in it, BTW.

Victor