c++ - Why are these default arguments allowed? -


i've found this question, , i'm baffled.

the answer says b invalid, "non-static members can not used default arguments.". makes perfect sense.

what don't understand why other 2 okay. in fact, i'm struggling understand semantics if default not constant expression...

what's going on here? default parameters evaluated @ compile time. compiler pick current value?

#include <iostream>  int g_x = 44;   struct foo  {    int m_x;    static int s_x;     foo(int x) : m_x(x) {}    int a(int x = g_x) { return x + 1; }    int b(int x = m_x) { return x + 1; }   int c(int x = s_x) { return x + 1; } };   int foo::s_x = 22;   int main(int argc, char** argv)  {    foo f(6);     std::cout << f.a() << std::endl;    std::cout << f.b() << std::endl;    std::cout << f.c() << std::endl;     return 0;  } 

actually, default arguments evaluated when function called, why okay. draft c++ standard section 8.3.6 default arguments says (emphasis mine going forward):

default arguments evaluated each time function called. order of evaluation of function arguments unspecified. consequently, parameters of function shall not used in default argument, if not evaluated. parameters of function declared before default argument in scope , can hide namespace , class member names.

the following example same section gives rationale why can use static members not non-static ones:

[ example: declaration of x::mem1() in following example ill-formed because no object supplied non-static member x::a used initializer.

int b; class x {     int a;     int mem1(int = a); // error: non-static member                          // used default argument     int mem2(int = b); // ok; use x::b     static int b; }; 

the declaration of x::mem2() meaningful, however, since no object needed access static member x::b. classes, objects, , members described in clause 9. —end example ]


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -