Sign in to follow this  
Quasius

C++: Accessing static class variables in member functions

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this