Default Argument Function in C++

C++ allows us to call a function with out specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching arguments in the function call.

Default values are specified when the function is declared .The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.


void moveTo( int x = 0, int y = 0);
void moveTo( int = 0, int = 0);

The function moveTo() can then be called with or without one or two arguments.

moveTo (); 
moveTo (24); 
moveTo(24, 50);

One important point to note is that only the trailing arguments can have default values. That is, we must add default from right to left. We cannot provide a default to a particular argument in the middle of an argument list.


int mul(int i, int j=5,int k=10);//illegal
int mul(int i=0,int j,int k=10);//illegal
int mul(int i=5,int j);         //illegal
int mul(int i=2,int j=5,int k=10);//illegal

Default arguments are useful in situation whose some arguments always have the some value. For example, bank interest may retain the same for all customers for a particular period of deposit.

Related posts