In C++, you can provide default values for function arguments. All default argument names of a function are bound when the function is declared. All functions have their types checked at declaration , and are evaluated at each point of call.
For example :
/** ** This example illustrates default function arguments **/ #include <iostream.h> int a = 1; int f(int a) {return a;} int g(int x = f(a)) {return f(a);} int h() { a=2; { int a = 3; return g(); } } main() { cout << h() << endl; }
This example prints 2 to standard output, because the a referred to in the declaration of g() is the one at file scope, which has the value 2 when g() is called. The value of a is determined after entry into function h() but before the call to g() is resolved.
A default argument can have any type.
A pointer to a function must have the same type as the function . Attempts to take the address of a function by reference without specifying the type of the function produce an error. The type of a function is not affected by arguments with default values.
The following example shows that the fact that a function has
default arguments does not change its type . The default argument
allows you to call a function without specifying all of the
arguments, it does not allow you to create a pointer to the
function that does not specify the types of all the arguments.
Function f can be called without an explicit argument, but the
pointer badpointer cannot be defined without specifying the type
of the argument:
int f(int = 0); void g() { int a = f(1); // ok int b = f(); // ok, default argument used } int (*pointer)(int) = &f; // ok, type of f() specified (int) int (*badpointer)() = &f; // error, badpointer and f have // different types. badpointer must // be initialized with a pointer to // a function taking no arguments.
Calling Functions and Passing
Arguments
Restrictions on C++ Default Arguments
Evaluating C++ Default Arguments