Question:
Consider the following code:
<code class="cpp">class Bar { public: static const int kConst = 1; void func() { foo(kConst); } }; int main() { Bar b; b.func(); }</code>
While compiling this code, an error occurs: "Undefined reference to 'Bar::kConst'". Why does this occur, and how can it be resolved?
Answer:
This error occurs because static const int members, if used (passed to functions or cast), must be defined in a namespace scope.
According to C 11 section 9.4.2/4:
"If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program."
Passing the static data member by const reference constitutes "use" according to C 11 section 3.2/2:
"An expression is potentially evaluated unless ... is the operand of the sizeof operator, ... or is the operand of the typeid operator and ... does not designate an lvalue of polymorphic class type. An object or non-overloaded function is used if its name appears in a potentially-evaluated expression."
However, GCC initially allowed passing static const members by const reference without defining them in a namespace scope. In C 0x drafts, this is no longer allowed.
A practical issue arises when taking addresses of or references to non-existent objects like static const members. This could lead to undefined behavior if they are called from multiple translation units.
To resolve this issue, the following modifications can be made:
Define the static const member in a namespace scope:
<code class="cpp">int bar::kConst = 1;</code>
Use static_cast
<code class="cpp">foo(static_cast<int>(kConst));</code>
The above is the detailed content of Why do I get an \'Undefined reference to \'Bar::kConst\'\' error when using a static const int member in a function?. For more information, please follow other related articles on the PHP Chinese website!