Jump to content
  • Advertisement
Sign in to follow this  
Quasius

C++: Accessing static class variables in member functions

This topic is 3872 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a class which needs some data which will always be the same for every instance of that class, so storing it separately for each instance is a waste of memory and I wanted it to be static. So it looks something like this:
Foo.h:

class Foo
{
    void DoSomething();

    static int m_Bar;
};

---------------------------------------------------------

Foo.cpp:

#include "Foo.h"

void Foo::DoSomething()
{
    m_Bar = 5;
}
This produces "error LNK2001: unresolved external symbol." I am using MSVC++ 2005 express. I tried messing around with extern, but didn't get anywhere. What is the correct syntax for what I'm trying to do? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
You have to define it (it has only been declared):



Foo.cpp:

#include "Foo.h"
int Foo::m_Bar = 0; // you miss this

void Foo::DoSomething()
{
m_Bar = 5;
}



Share this post


Link to post
Share on other sites
In exactly one source file (Foo.cpp would be the natural place):


int Foo::m_bar = /* initial value */;



The header file is fine.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!