Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Access private static member from public static method? [duplicate]

Tags:

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

like image 683
SLC Avatar asked Aug 25 '13 21:08

SLC


1 Answers

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; 
like image 175
Pierre Fourgeaud Avatar answered Sep 22 '22 05:09

Pierre Fourgeaud