Default arguments in C++ functions (C++ only)

You can provide default values for function parameters. For example:

#include <iostream>
using namespace std;

int a = 1;
int f(int a) { return a; }
int g(int x = f(a)) { return x; }

int h() {
  a = 2;
  {
    int a = 3;
    return g();
  }
}

int 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 default argument must be implicitly convertible to the parameter 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 will produce an error. The type of a function is not affected by arguments with default values.

The following example shows that default arguments are not considered part of a function's 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.

In this example, function f3 has a return type int, and takes an int argument with a default value that is the value returned from function f2:

      const int j = 5;
      int f3( int x = f2(j) );

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]