Search code examples
c++public

How do I use public member variable outside class?


class A {
   public:
     int VARIABLE = 0;
};

How do I use the public variable inside the function of another class? In Java a public variable can be accessed by using the class name and the dot-operator. Is there something similar in C++?


Solution

  • I think you are referring to static members. In C++ it is done as:

    // A.h
    class A {
       public:
         static int VARIABLE = 0;
    };
    
    
    // B.h
    #include "A.h"
    
    class B {
      public:
        void foo() {
          A::VARIABLE = 5; // < here
        }
    };
    

    To summarize comments, the operator you are looking for is the Scope Resolution Operator: