tags:

views:

89

answers:

3
class B {
 public:
   static int a;
};
class C:B {
};

I want to use a variable through any inherited classes but it has problem when I declare a.

B::B() {
  a=1;
};

Do I do it right ?
Thanks for reading and waiting for your comments.

// I miss semicolons which is not the error I'm talking . // This is an error when I try to delcare class GameState { public: static int a = 1; //... };

Error   7   error C2864: 'CGameState::a' : only static const integral data members can be initialized within a class    d:\my dropbox\work\#today\gdimario\gdimario\gamestate.h 18

I try to write a simple question which shows the problem I want instead of pasting my whole code.

+5  A: 

You can use it directly like you did from both the derived and base class.

Perhaps your error is that you don't have semicolons at the end of your class declarations?

class B {
 public:
   static int a;
};

class C:B {
};

If you want to call it from an instance of C then you need to use public inheritance: (If nothing is specified private inheritance is assumed)

class C : public B {
};

To initialize a you need to do this (typically at the top of your corresponding .CPP file):

int B::a = 3;
Brian R. Bondy
Shouldn't it be `C::B` as well ?
ereOn
@ereOn: Where do you mean?
Brian R. Bondy
@Brian R. Bondy: Never mind... Hadn't sleep enough ;)
ereOn
+3  A: 

You need to write in a CPP file:

int B::a;

And add the semicolons that Brad suggests. (Did you even compile your code? What did the compiler say?)

Daniel Daranas
Can he really write this in the class **definition** ? `a` is not `const`, just `static`.
ereOn
@ereOn I'm not sure, but I think that initialization part is because the member variable is static - not only for constants.
Daniel Daranas
@ereOn yes "static int a = 1;" just gives it an initial value. The fact that it's not "const" means that value can be changed later.
joefis
@joefis: You know exactly what I want. The fact that, I declare a variable which I'll do a lot of with it.
nXqd
@Daniel: Error 12 error LNK2001: unresolved external symbol "public: static int CGameState::a" (?a@CGameState@@2HA) GameState.objThis is an error when I declare in my CGameState::CGameState { CGameState::a = 1;} . Which is no different with CGameState::CGameState { a = 1;}
nXqd
Only `const` static members can be supplied with an initializer directly in the class definition.
AndreyT
@AndreyT You're right. I'll edit my answer now to fix it.
Daniel Daranas
A: 

i think you ll get linker error. since you have not defined of the static variable in the .cpp file.

e.g.

//hearer file
class X{

 public : static int a ;

}
//impl file

int X::a(0);

....or...

For integral type you can also defined static variables when they are declared like:

class X{

 public : static int a  = 0;

}
Ashish
Only `const` static members can be supplied with an initializer directly in the class definition. Also, even if it has an initializer, it is still not a definition.
AndreyT