Why can't static const float members be initialized in a class?

Started by
27 comments, last by SiCrane 12 years, 1 month ago
Well i was just creating my particle engine in OpenGL and i thought of using classes instead of Structs, and i eventually ran into this static const float..
I never knew they could not be initialized in Class,

For ex,


class cType
{
private:
static const int Num = 10; // Ok.
static const float color = ... // Error
};


Any reasons why?
Thanks!
Advertisement
In C++ there is no meaningful difference between class and struct.

Any reasons why?[/quote]

Standard says so. There's likely obscure technical reasons for it, but there is no conspiracy of universe why it could not be done.
If you don't want to separate the definition and the declaration, you can go with the function approach.
[source]
class cType
{
private:
static const int Num = 10; // Ok.
static float color() {return ... ;}
};
[/source]
Or upgrade to C++11 and use constexpr.
Is it because float is old-school..
Because i can use

static const long color = ... //Works like a charm.
As Antheus said, it's because the standard says so. It simply allows for integer types only to be initialized like that, so floating point types have to be defined the normal way with separate definition in a single translation unit. At least pre-C++11...
No, it's because float isn't a integral or enumeration type. Under C++03 those were the only kinds of static data members you could initialize in the body of a class or struct.
Thanks guys!
Its funny how except double and float almost every numerical constants work..
That's because they are integral constants.
And another thing, Is long-float termed as double, because i got an error message when i used long float in class initializer


static const long float num = 10.0;
Error: a member of type "const double" cannot have an in-class initializer; //Wth?

This topic is closed to new replies.

Advertisement