3

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.

max66
  • 65,235
  • 10
  • 71
  • 111
  • Would there be any repercussions if you used `const int i = 123;` inside your structure? i.e., remove the `static` keyword? – Logicrat Apr 27 '16 at 18:45
  • @Logicrat: without `static`, no errors (only a couple of warning compiling with c++98 because only from c++11 you can initialize in this way a not static variable) – max66 Apr 27 '16 at 18:56
  • @David: I suppose you're right: the question is little different but the background is the same and the answer are good for my question too. What I'm supposed to do in this (duplicate question) case? I should delete the question? – max66 Apr 27 '16 at 19:00
  • @max66 You don't have to do anything, it's all good. Just leave your question here - it may be useful to someone in the future even marked as duplicate – David Apr 27 '16 at 19:12

0 Answers0