Reputation: 1473
I'm declaring a class which needs some public constants. My idea was declaring ones just like this:
class MyClass {
public:
const int kIntConst = 1234;
const float kFloatConst = 1234.567f;
// ...methods...
};
This approach works fine for int
constant but fails for the float
one with the following error:
error C2864: 'MyClass::kFloatConst' : only static const integral data members can be initialized within a class
Well, I do understand this error message. It says I cannot have a float (non-integral) constant declared in the class declaration. So, the question is: WHY!? Why it can be int
but not float
?
I know how to workaround this. Declaring kFloatConst
as a static const member and later initialization in .cpp solves the problem but this is not what I'd like to have. I need a compile time constant (a one which can be optimized by compiler), not a constant class member which needs .obj file linking.
Using macro could be an option but macro doesn't have namespace and I don't like globally defined constants.
Upvotes: 0
Views: 197
Reputation: 92301
The general rule is that you cannot have constants defined inside the class declaration.
Then there is an exception that integral constants are allowed anyway. So the int
constant isn't the rule, but the exception.
Upvotes: 2