Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static constant members for array size

Tags:

c++

MyClass.h

class MyClass
{
public:

static const int cTotalCars;

private:

int m_Cars[cTotalCars];
};

MyClass.cpp

#include "MyClass.h"
const int MyClass::cTotalCars = 5;

The above code doesn't work because it will say "expected constant expression" for the m_Cars array.

class MyClass
{
public:

static const int cTotalCars = 5;

private:

int m_Cars[cTotalCars];
};

The above will work, but I am told that I should always define static members in the CPP file, outside the class definition. What can I do?

like image 964
user987280 Avatar asked Oct 10 '11 08:10

user987280


1 Answers

Static const members of simple type are a exception to that rule, so you latter code is correct.

This exception is a fairly modern one (from C++98, but not implemented by every compiler until a few years later) so many old-fashioned teachers are not yet aware of it. They prefer the idiom:

class MyClass
{
public:
   enum { cTotalCars = 5 };

private:
    int m_Cars[cTotalCars];
};

That behaves exactly the same, but makes little sense nowadays.

like image 147
rodrigo Avatar answered Oct 02 '22 19:10

rodrigo