0

Look at this very basic c++ class:

class MyClass {
 public:
  static std::map<int, std::string> test;

  void method1()
  {
     std::cout << test[1] << std::endl;
  }
};

int main()
{
    MyClass::test[1]="test";  

    return 0;
}

As you can see, this very basic class contains a static field. But when i am trying to access it, i get this compiler error:

undefined reference to `MyClass::test[abi:cxx11]'

In order to make it work, i have tried to create a static method and declare my static field inside this method. It works, but it looks ugly. I want to understand why my first code does not work and why this second code works...

class MyClass {
 public:
  static std::map<int, std::string>  get_test()
  {
    static std::map<int, std::string> test;
    return test;
  }

  void method1()
  {
     std::cout << get_test()[1] << std::endl;
  }
};

int main()
{
    MyClass::get_test()[1]="test";

    return 0;
}

Thanks

Bob5421
  • 7,757
  • 14
  • 81
  • 175
  • 3
    You only have a *declaration* of the static member, there's no definition of it. Every book or tutorial discussing static members should have told you what to do, please don't skip parts of your books, tutorials or classes. – Some programmer dude Jan 23 '19 at 14:12
  • 1
    By the way, if you make `get_test()` return by reference, that actually _is_ the preferred way to do it, if you don't mind a little overhead. It avoids the static initialisation order fiasco, among other things. – Lightness Races in Orbit Jan 23 '19 at 14:17
  • @LightnessRacesinOrbit Not to mention that the OP won't have to wonder why the data he or she added to the map seems to disappear all the time. :) – Some programmer dude Jan 23 '19 at 14:20

0 Answers0