I've found this question, and I'm completely baffled.
The answer says b
is invalid, "Non-static members can not be used as default arguments.". That makes perfect sense.
What I don't understand is why the other two are okay. In fact, I'm struggling to understand what the semantics are if the default is not a constant expression...
What's going on here? Default parameters are clearly evaluated at compile time. Does the compiler simply pick the 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 are evaluated when the function is called, which is why this is okay. From the draft C++ standard section
8.3.6
Default arguments which says (emphasis mine going forward):The following example from the same section gives us a rationale for why we can use static members but not non-static ones: