C++ Access private static member from public static method?

Sandu Liviu Catalin picture Sandu Liviu Catalin · Aug 25, 2013 · Viewed 19.4k times · Source

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

Answer

Pierre Fourgeaud picture Pierre Fourgeaud · Aug 25, 2013

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;