I have been reading "Exceptional C++" by Herb Shutter, "Item 1 : #define or const and inlining [...]".
It is said that the in-class initialization is allowed only for integral types(integers,chars,bools) and only for constants..
I just want to know why double/float cannot be initialized in class declaration. Are there any specific reasons?
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR;
...
};
// this goes in the class implementation file
const double EngineeringConstants::FUDGE_FACTOR = 1.35;
I just want to know the reason why the below declaration is not allowed:
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR = 1.35;
...
};
?
This statement is outdated: in C++03 initialization using double
s in the class definition was not supported. In C++ (starting with the 2011 revision), you can initialize arbitrary members in the class definition. Also, the initialization isn't limited to static
members but you can also initialize non-static
members:
struct foo {
static constexpr double value = 1.23;
std::string str = "foo";
};
The historic reason to prohibit initialization of static
members using floating point numbers in C++03 was that the numeric during compilation could be different than those during execution. For example, when cross compiling on a platform using IEEE floating points and targeting a platform using IBM hex floats could yield different results even for constants representable in both numeric systems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With