Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why double is not allowed in in-class initializer

Tags:

c++

oop

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;
  ...
 };

?

like image 472
ATul Singh Avatar asked Sep 28 '13 16:09

ATul Singh


1 Answers

This statement is outdated: in C++03 initialization using doubles 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.

like image 101
Dietmar Kühl Avatar answered Oct 19 '22 23:10

Dietmar Kühl