I'm a little confused about static class/struct member declaration/initialization.
I was convinced that it's necessary declare a static member inside the class/struct body and initialize it outside. With an important exception: it's possible declare and initialize a static member inside the class/struct body if the member (a) is const and (b) is of integral type (bool
, int
, long
, etc.).
So (I was convinced that) it's perfectly legal something like
struct foo
{ static const int i = 123; };
And it works, in the following example
#include <iostream>
struct foo
{
static const int i = 123;
void baz (const int j)
{ std::cout << "baz: j = " << j << '\n'; }
void bar ()
{ baz(foo::i); }
};
int main ()
{
foo().bar();
return 0;
}
But if I change the definition of foo::baz()
method passing the argument j
as reference
void baz (const int & j)
{ std::cout << "baz: j = " << j << '\n'; }
I find that foo::i
is undefined. And this with g++
(4.9.2), with clang++
(3.5.0), compiling as c++98, as c++11 or as c++14. In all cases i get the following linker error: riferimento non definito a "foo::i"
(italian for "undefined reference to \"foo::i
\"").
If I declare only the static member inside
//static const int i = 123;
static const int i;
and initialize it outside the body of the struct,
const int foo::i = 123;
no more errors and the program work as expected.
So... why?
It's me (I don't understand the static member initialization?) or are the compilers (a bug of g++
and clang++
?)?
p.s.: sorry for my bad English.