Static Member Variable?

L

Leo

I have a member function in this class, which needs a variable to keep
track its status. Thus I used a static member variable.

But I encounter a "unresolved external variable" error during compile
(for the variable a).

Can anyone tell me what I did wrong?


////////////// testclass.h
#pragma once

class testclass
{

public:

// constructor and destructor
testclass(void);
~testclass(void);

// static part
static int a;
static void test(void);

};




////////////// testclass.cpp

#include "testclass.h"

testclass::testclass(void)
{
}

testclass::~testclass(void)
{
}

void testclass::test(void)
{
// problem appears after I put this line
a=1;
}
 
R

Ron Natalie

Leo said:
But I encounter a "unresolved external variable" error during compile
(for the variable a).

You don't define the variable testclass::a anywhere. You get away with it
as long as nobody uses it.

in testclass.cpp (after the #include)
put
int testclass::a;

You can give it an initializer if the default (zero) is not appropriate.
 
C

Calvin Lai

But how come this is not necessary for non-static members? (that we just
need to *declare* them in the header file);
 
V

Victor Bazarov

Calvin Lai said:
But how come this is not necessary for non-static members? (that we just
need to *declare* them in the header file);

Because you "define" them when you define an instance of the class.
They are created along with an object of the class. Heck, an object
of the class _consists_ of them, without them it wouldn't be.

Please don't top-post.
 
J

Jeff Schwab

Calvin said:
But how come this is not necessary for non-static members? (that we just
need to *declare* them in the header file);

"Define" is being used here to mean "allocate storage." Storage for
non-static member variables is provided as part of each instance of the
class. Since static member variables by definition do not correspond to
any instance, you have to state explicitly where they should be stored.
 
R

Ron Natalie

Calvin Lai said:
But how come this is not necessary for non-static members? (that we just
need to *declare* them in the header file);

Because they are created with each object as it is created (it's part of the object).
The non-static members have to be put some where exactly once.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top