Mut...@dastardlyhq.com wrote:
> In a similar vein, why does C++ still insist on class static values being set
> outside of the class? eg:
>
> struct myclass
> {
> static int i;
> };
>
> int myclass::i = 123;
>
> Why on earth can't I just do:
>
> struct myclass
> {
> static int i = 123;
> };
As you probably know, 'static' variables declared inside a class aren't
actually member variables, but free-floating variables which visibility
scope is inside that class (the term "class variable" is often used for
these types of variables, in many OO languages, as opposed to "member
variable").
The 'static int i;' in the class definition is just a declaration, and
it needs to be actually defined, ie. instantiated somewhere, in one
(and only one) compilation unit. If you don't instantiate it somewhere
the compiler will be unable to decide where to instantiate it and you'll
get a linker error because it has only been declared but not instantiated
in any compilation unit.
C++17 extended the 'inline' functionality, which does that automatically
for you (so that you don't have to instantiate the variable by hand),
but prior to it you had to do it yourself.
I suppose that when C++98 was standardized it was decided that it's
better to specify the initial value of that 'static' variable where
it's instantiated rather than where it's declared. (I suppose that
technically speaking it wouldn't be hard for compilers to look up
the initial value from either one, because to instantiate the variable
it needs to see the declaration.) Perhaps it was thought that it causes
less confusion because if it's initialized in the declaration it may
look like it will be initialized to that value every time the class
is instantiated (which, of course, is not the case).
> in the same way that const members are initialised? I've never seen a good
> reason why it must be this way and it makes for messy header files.
I don't think const member variables can be initialized in the class
definition in C++98. That syntax was only introduced in C++11.