Why does not in-class “const int m = 2;” compile (C2864)?


This doesn’t compile (error C2864).

struct CMyClass
{
    const int m = 2;
};

It requires ‘static’. But why?

IMO, it’s because this brings up a problem to the compiler.
The compiler has to inject code into the constructor to initialize m, just as injecting a base constructor call to sub constructor. By making m static, m is simply in the data section of the executable file.
In C++11, this piece of code is no longer an error.

Advertisements
Comments are closed.
%d bloggers like this: