2

So I just had a question, In c++11 why do I have to specify the type of a static member to assign to it a value?

Example:

class Player
{
   static size_t numOfObj;
public:
   Player(){numOfObj++;}
   ~Player(){numOfObj--;}
}

size_t Player::numOfObj = 0;

In this case why do I have to specify again that numOfObj is of type size_t, can't I just do Player::numOfObj = 0; due to it being already declared?

Thanks in advance.

5
  • @idclev463035818 updated Commented Mar 27, 2020 at 18:14
  • 1
    Note that in C++17 you can just assign the value within the class, and not repeat yourself at all. Commented Mar 27, 2020 at 18:16
  • @einpoklum yeah I know, but I just wanted to see why we have to do this in that case :) Commented Mar 27, 2020 at 18:18
  • @idclev463035818 yes, however it is a duplicate itself aswell. Commented Mar 27, 2020 at 18:25
  • i cleaned up my comments a bit, yes you can answer your own question, to my experience a bit higher standards are put on self-answered questions, but in principle there is nothing wrong with answering your own question Commented Mar 27, 2020 at 18:44

1 Answer 1

3

size_t Player::numOfObj = 0; is syntax for definition. A (non-inline) static variable must be defined exactly once in exactly one translation unit. Not more, and not less (unless the variable is unused).

can't I just do Player::numOfObj = 0; due to it being already declared?

You can do that. But not in the namespace scope because that is syntax of an expression statement. Expression statements may not be in the namespace scope. They are allowed only in a block scope. The meaning of this expression is that the value of the variable is assigned. Assignments can be done as many times and in as many translation units as you like (as long as the type is non-const and assignable).

So, if definition had this syntax, there would be conflict with the syntax already having another meaning. That would be undesirable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.