Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const static member initialization - inside vs outside class definition [duplicate]

Tags:

c++

stl

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?

like image 993
Ramon Avatar asked Jun 22 '26 07:06

Ramon


1 Answers

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.

like image 105
R Sahu Avatar answered Jun 24 '26 21:06

R Sahu