3

I know that static literal type members can be initialized in the class definition, and non-literal types can't.

class Class 
{
    static const int lt = 0; //OK
    static const std::string nlt = "hello"; //compilation error
};

However, I ran into a weird issue, where I can't use the members in STL containers if they are initialized inside the class definition, as opposed to outside.

class Class
{
public:
    static const int var = 1;
    void f();
};

void Class::f() {
    std::vector<int> vec;
    vec.push_back(var);
}

The example above results in the linker error undefined reference to Class::var If I move the initialization outside, the error goes away.

const int Class::var = 1;

What are the differences between the two initializations above? Why does one cause the error with stl containers?

Ramon
  • 1,169
  • 11
  • 25

1 Answers1

4

What are the differences between the two initializations above? Why does one cause the error with stl containers?

The argument type of std::vector<int>::push_back() is int const&. Whenever a variable is used by reference or pointer, it must be defined.

A simple change to Class::f implementation will obviate the need to define Class::var.

void Class::f() {
   std::vector<int> vec;
   int v = var;
   vec.push_back(v);
}

Here, var is not used by reference. Hence, there is no need to define Class::var.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks. Also, defining it outside the class with the initialization in the declaration works `const int Class::var;` This allows the clarity of the values in the header, but it can still be referenced. – Ramon Feb 03 '16 at 21:20
  • As well, creating a temporary `vec.push_back((int)var)` is pretty readable, and doesn't need the definition. – Ramon Feb 03 '16 at 21:24