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

20,482

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;
Share:
20,482

Related videos on Youtube

SLC
Author by

SLC

Updated on August 26, 2020

Comments

  • SLC
    SLC over 3 years

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

    • sehe
      sehe over 10 years
      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.
  • SLC
    SLC over 10 years
    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)
  • Pierre Fourgeaud
    Pierre Fourgeaud over 10 years
    @SanduLiviuCatalin So your problem is solved now ? An example of this working :)
  • SLC
    SLC over 10 years
    Yes. I'm waiting to become 15 minutes old so that I can mark it as solved.