C++ Default Arguments Bob Walton, 7/16/96 In C++, because function overloading is allowed, the following is possible: int sum ( int x, int y ) { return x + y; } int sum ( int x, int y, int z ) { return x + y + z; } int sum ( int x, int y, int z, int w ) { return x + y + z + w; } This permits the calls: sum ( 1, 2 ) sum ( 1, 2, 3 ) sum ( 1, 2, 3, 4 ) The following is also allowed in C++: int sum ( int x, int y, int z = 0, int w = 0 ) { return x + y + z + w; } The value given after the = sign for an argument is the default value for the argument in case the argument is omitted. This makes the argument optional. With this last definition of sum: sum ( x, y ) is equivalent to sum ( x, y, 0, 0 ) sum ( x, y, z ) is equivalent to sum ( x, y, z, 0 ) Default values may only be given to arguments at the end of the argument list. Arguments may only be omitted from the end of an actual argument list, and then only if default values are given. The declaration: int sum ( int x, int y, int z = 0, int w = 0 ); in effect declares three sum functions with 2, 3, and 4 arguments. There must not be other declarations that conflict with these. Default argument values should be given only in .h files, or when the function is first declared in a translation unit (i.e. a .cc file and its inclusions). Thus if the above declaration for sum is given in a .h file included in a .cc file, a definition of sum in the .cc file should have no default argument values, as in: int sum ( int x, int y, int z, int w ) { return x + y + z + w; } Default argument values may be expressions that reference global and static expressions and functions. They are evaluated separately every time the function is called. Names used in these expressions are interpreted in the scope they appear in; i.e., the name refers to what it refers to where the default argument value appears in the program code, and not what it might refer to where the function is actually called.