Accessing static member variables

Get answers to all your basic programming questions. No Ogre questions, please!
saetrum
Halfling
Posts: 60
Joined: Fri Oct 24, 2003 6:39 pm
x 1

Accessing static member variables

Post by saetrum »

I have base class that has a protected static member variable.

I'd like to access that variable from a non static function from within a class that inherits the base class. How would I do that?

for example:

class State
{
public
...
protected:
static SceneManager * gSM;
...
}

class GameState : public State
{
public:
void function();
...
}

void GameState ::function()
{
State::gSM->doSomething();
}


This gives me linking errors - unresolved symbol. So any ideas?
User avatar
epopov
Halfling
Posts: 85
Joined: Tue Jun 10, 2003 2:57 pm

Post by epopov »

Your code is fine (regarding the static variable access): linker errors mean you have probably forgotten to add some .cpp files in your project. You will have to paste the full error so we can narrow the problem down.
saetrum
Halfling
Posts: 60
Joined: Fri Oct 24, 2003 6:39 pm
x 1

Post by saetrum »

:oops: I neglected to declare the variables before I initialized them. I didn't realize that I had to actually declare the static variables at file scope before using a static function to initialize - i.e.

Code: Select all

class State 
{ 
public 
... 
protected: 
static SceneManager * gSM; 
... 
} ;
//**********FORGOT this line below**********
SceneManager * State::gSM = NULL;

class GameState : public State 
{ 
public: 
void function(); 
... 
} 

void GameState ::function() 
{ 
State::gSM->doSomething(); 
} 
UT2007
Kobold
Posts: 31
Joined: Fri Feb 17, 2012 10:09 am
x 5

Re:

Post by UT2007 »

saetrum wrote:

Code: Select all

class State 
{ 
public 
... 
protected: 
static SceneManager * gSM; 
... 
} ;
//**********FORGOT this line below**********
SceneManager * State::gSM = NULL;

class GameState : public State 
{ 
public: 
void function(); 
... 
} 

void GameState ::function() 
{ 
State::gSM->doSomething(); 
} 

This piece of code helped me to solve an important issue, i give you KUDO for this ! (idea to have NULL for scenemanager was not so evident in the fire of action)