c++ static member method with default argument

c++, default-arguments, static

Solution

Technically, I would use:

static void method1( int a, Index b = INDEX_A);

but other than that, static functions are no different from any other functions. They just don't have the "hidden" `this` parameter passed in, so the function is not called with an instance of the class.

Note also that when using default arguments, you can get REALLY fun stuff if you later define your function, using this:

static void method1( int a, Index b = INDEX_B)
{
  ...
}

because, depending on where you call the function, you may have `b` with a value of `INDEX_A` or `INDEX_B` (if you call it before the definition, or in a different translation unit, it will be `INDEX_A`, if you call it after definition, it will probably be `INDEX_B`). The argument is filled in by the compiler at the point of the call.

Your comments about static member applies to static member VARIABLES. Member functions exist as soon as the code is compiled and linked. Normal member variables are created when the class is instantiated, e.g. when the code executes the code for `foo x` or `foo *p = new foo;`). Static member variables have "global storage duration", in other words, they are like global variables, just that their "name" is inside the class, rather than regular global variables.

And yes, you have to worry about order of initialization when it comes to static member variables, if you are using them between translation units (different source files = different translation units). The order of initialization is undefined (by the standard) between different TUs.

Problem

Are there any pitfalls if we use default argument for static member variable? Like this: ``` enum Index { INDEX_A = 0, INDEX_B }; class foo { public: static void method1( int a, int b = INDEX_A); }; ``` Compiler never complains, but I am always cautious when it is anything to do with static.

Original source