23

Let's say I have a .hpp file containing a simple class with a public static method and a private static member/variable. This is an example class:

class MyClass
{
public:
    static int DoSomethingWithTheVar()
    {
        TheVar = 10;
        return TheVar;
    }
private:
    static int TheVar;
}

And when I call:

int Result = MyClass::DoSomethingWithTheVar();

I would expect that "Result" is equal to 10;

Instead I get (at line 10):

undefined reference to `MyClass::TheVar'

Line 10 is "TheVar = 10;" from the method.

My question is if its possible to access a private static member (TheVar) from a static method (DoSomethingWithTheVar)?

SLC
  • 2,167
  • 2
  • 28
  • 46
  • 5
    it's got nothing to do with access or privateness. It has to do with absense of a definition of `TheVar`. It's only been declared. – sehe Aug 25 '13 at 21:13

1 Answers1

25

The response to your question is yes ! You just missed to define the static member TheVar :

int MyClass::TheVar = 0;

In a cpp file.

It is to respect the One definition rule.

Example :

// Myclass.h
class MyClass
{
public:
    static int DoSomethingWithTheVar()
    {
        TheVar = 10;
        return TheVar;
    }
private:
    static int TheVar;
};

// Myclass.cpp
#include "Myclass.h"

int MyClass::TheVar = 0;
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
  • Thank you for the answer :) I tried that however I always get an error saying that I cannot access TheVar because it was private. The reason was that I always forgot to put the type (int) at the beginning so the compiler probably thought I want to access that private member. (Epic mistake sorry to bother) – SLC Aug 25 '13 at 21:22
  • @SanduLiviuCatalin So your problem is solved now ? [An example](http://ideone.com/V58sWe) of this working :) – Pierre Fourgeaud Aug 25 '13 at 21:24
  • Yes. I'm waiting to become 15 minutes old so that I can mark it as solved. – SLC Aug 25 '13 at 21:25