I have a hyerarchy of classes. Methods of these classes may create temporary static arrays of the same size. I want to set size as static const field of the base class.
I put declaration of the field in a heared file and initialized it in a source file. This works without issues when compiled using GCC 4.3 but fails with VS compiler.
Base.h
class Base
{
public:
virtual void function();
protected:
static const int size;
};
Base.cpp
#include "Base.h"
const int Base::size = 128;
void Base::function()
{
int array[size];
}
Derived.h
#include "Base.h"
class Derived : public Base
{
void function();
};
Derived.cpp
#include "Derived.h"
void Derived::function()
{
int array[size];
}
Main.cpp
#include "Derived.h"
int main()
{
Base* object = new Derived();
object->function();
return 0;
}
I expected that size would be initialized in Base.cpp and considered as const in Derived.cpp. But it works only with GCC compiler.
Visual Studio shows the following error messages:
error C2131: expression did not evaluate to a constant
note: failure was caused by non-constant arguments or reference to a non-constant symbol
note: see usage of 'size'
Derived::function,sizeis still unknown (any maybe even impossible to determine in compile time). (although I'm not sure what the standard say)variable length array?sizeconstexprand initialize it inBasedeclaration.