0

Is a simple example in order to use some static field in a class.

#ifndef FOOCLASS_H_
#define FOOCLASS_H_

#include <string>

class FooClass {
 public:
    FooClass();
    virtual ~FooClass();

    std::string getMessage();

    void modifier();
    static void modifier_st();
    static std::string getStaticMessage();
  private:
    static std::string message_static;
    std::string message;
  };

and cpp file with implementations of methods is

  #include "FooClass.h"

  FooClass::FooClass() {
      message = "";
  }

  FooClass::~FooClass() {
      // TODO Auto-generated destructor stub
  }

  std::string FooClass::getMessage(){
      return "Message is:" + message;
  }

  void FooClass::modifier(){
      message += " sample ";
  }

  void FooClass::modifier_st(){
      message_static += " sample static ";
  }

  std::string FooClass::getStaticMessage(){
      return "Message is:" + message_static;
  }
  #endif /* FOOCLASS_H_ */

I compiled that code with g++.

In the last methods appear error "undefined reference to `FooClass::message_static[abi:cxx11]'".

What is the explanation of that error? What other alternatives is to develop last two methods?

Mihai8
  • 3,113
  • 1
  • 21
  • 31
  • 1
    You need to *define* your static variable, the code above only *declares* it. – john Feb 16 '19 at 21:45
  • The static variable needs to be defined in one .cpp file, or if you are using c++17 you can make it inline. – super Feb 16 '19 at 21:47

0 Answers0