Search code examples
c++implementationstatic-variables

c++ access private static member from implementation file


I have a header file like so

#ifndef MYAPP
#define MYAPP
#include <map>
namespace MyApp{
    class MyClass{
        private:
            static std::map<int, bool> SomeMap;
        public:
            static void DoSomething(int arg);
    };
}
#endif MYAPP

and an implemtation file

#include "Header.h"
#include <map>
namespace MyApp{
    void MyClass::DoSomething(int arg){
        if(MyClass::SomeMap[5]){
            ...
        }
    }
}

When I tried to compile it, it gives me an error class "MyClass" has no member "SomeMap". How can I fix this?


Solution

  • You have forgotten to define your static variable:

    #include "Header.h"
    #include <map>
    namespace MyApp{
        std::map<int, bool> MyClass::SomeMap;
    
        void MyClass::DoSomething(int arg){
            if(MyClass::SomeMap[5]){
                ...
            }
        }
    }
    

    P.S. Your example code is missing ; after class definition.