void some_func(int param = get_default_param_value());
views:
425answers:
2
+6
A:
Must not! default parameter can be any expression. It evaluates every time the function is called.
I just discovered that:)
Sergey Skoblikov
2008-12-02 18:05:09
+5
A:
Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or static class variables, but not member attributes.
The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call.
// Code 1: Valid and invalid default parameters
int global = 0;
int free_function( int x );
class Test
{
public:
static int static_member_function();
int member_function();
void valid1( int x = free_function( 5 ) );
void valid2( int x = free_function( global ) );
void valid3( int x = free_function( static_int ) );
void valid4( int x = static_member_function() );
void invalid1( int x = free_function( member_attribute ) );
void invalid2( int x = member_function() );
private:
int member_attribute;
static int static_int;
};
int Test::static_int = 0;
// Code 2: Variable scope
int x = 5;
void f( int a );
void g( int a = f( x ) ); // x is bound to the previously defined x
void h()
{
int x = 10; // shadows ::x
g(); // g( 5 ) is called: even if local x values 10, global x is 5.
}
David Rodríguez - dribeas
2008-12-02 20:21:46
Thanks a lot for good clarification of issues.
Sergey Skoblikov
2008-12-02 22:05:26
I didn't realize you could refer to global variables. Good resources at http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr237.htm and http://msdn.microsoft.com/en-us/library/e1dbzf09(VS.80).aspx .
Max Lybbert
2008-12-02 23:20:22
It can also be a call through a function pointer, ie. if foo(int arg=(*fp)()); Here, fp is looked up in the scope where foo is declared, but *fp is evaluated every time foo() is called.
MSalters
2008-12-03 14:07:43