static keyword

I was reading through static keyword usage.
I came across this explanation - "An important detail to keep in mind when debugging or implementing a program using a static class member is that you cannot initialize the static class member inside of the class. In fact, if you decide to put your code in a header file, you cannot even initialize the static variable inside of the header file; do it in a .cpp file instead. Moreover, you are required to initialize the static class member or it will not be in scope."

My question is, why can't we initialize static class member inside the class? Why should it always be outside the class?
If it is in a header, then it is initialized in every translation unit that includes it. Then linker should decide which one to keep. What if some copies are in dynamic libraries?

Things are kept simple by forcing the initialization into single place.
@keskiverto: My question is why we cannot initialize static class member inside the class. Let me give an example for more clarity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class user
{
  private:
  int id;
  static int next_id;

  public:
  static int next_user_id()
  {
    next_id++;
    return next_id;
  }
  /* More stuff for the class user */
  user()
  {
    id = user::next_id++; //or, id = user.next_user_id();
  }
};
int user::next_id = 0;


This was the code provided in cprogramming tutorials. My question is why can't I do static int next_id = 0; inside class user? Why should it be outside the class?
Last edited on
Topic archived. No new replies allowed.