The above will work, but I was told that I should always define static members in the CPP file, outside the class definition. What can I do?
Good thing you were asked to: define static members in CPP. Note that in the above code, the static member has no , even if the value is specified. The correct final code would look like this:
The definition in the .cpp file is what actually reserves space for the variable when using lvalue as the value. For a simple test that checks that a variable is not defined without this line, you can do:
void f( const int & x ) {} int main() { f( MyClass::cTotalCars ); }
Without a line in the .cpp file, the above code will throw a linker error indicating a missing MyClass::cTotalCars
. The problem with the code is that it uses the static member const (as defined by use in the standard) and requires that the member be defined. Although the case of using a constant to determine the size of the array is not used.
source share