Note that there are some explanatory texts on larger screens.

plurals
  1. POGlobal const initializing and difference between constructor in .h or .cpp file
    text
    copied!<p>I was wondering why sometimes my global const defined in seperate .h file isn't properly initialized when I need it. Some tests lead me to situation that I can't understand. I don't know how to explain it, so here's the code:</p> <h3>main.cpp</h3> <pre><code>#include &lt;iostream&gt; #include "class.h" using namespace std; A a; B b; int main(int argc, char* argv[]){ A aa; B bb; cout&lt;&lt;a.a&lt;&lt;" "&lt;&lt;aa.a&lt;&lt;endl; cout&lt;&lt;b.b&lt;&lt;" "&lt;&lt;bb.b&lt;&lt;endl; return 0; } </code></pre> <h3>class.h</h3> <pre><code>#ifndef CLASS_H #define CLASS_H #include "const.h" class A { public: A(); float a; }; class B { public: B():b(CONST){} float b; }; #endif </code></pre> <h3>class.cpp</h3> <pre><code>#include "class.h" A::A() : a(CONST){} </code></pre> <h3>const.h</h3> <pre><code>#ifndef CONST_H #define CONST_H #include &lt;limits&gt; using namespace std; const float CONST = numeric_limits&lt;float&gt;::has_infinity ? -numeric_limits&lt;float&gt;::infinity() : -numeric_limits&lt;float&gt;::max(); #endif </code></pre> <p>After running above code I get:</p> <blockquote> <p>0 -1.#INF<br> -1.#INF -1.#INF</p> </blockquote> <p>when actually I would like to get 4 times '-1.#INF'. Why does it happen this way? If CONST would be '1' instead of above formula, it would work perfectly.</p> <p>I can "fix" it by making static getConst() method:</p> <pre><code>static float getConst(){ static const float CONST = numeric_limits&lt;float&gt;::has_infinity ? -numeric_limits&lt;float&gt;::infinity() : -numeric_limits&lt;float&gt;::max(); return CONST;} </code></pre> <p>but it just doesn't "feel" right. On other hand I just need two of those above... But maybe there's some other way?</p> <p>And, most importantly, why class B gets "right" CONST and class A don't?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload