(This question has been asked in GU Uni Dec 2018 for 7 Mark)

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value.

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value.

Following is a simple C++ example to demonstrate the use of default arguments. We don’t have to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.

Following is a simple C++ example to demonstrate the use of default arguments. Note that main function is calling the same function called myFun in two different place. First time it is called with only one argument so that value will be passed to x, because second parameter is not passed compiler will take consider the default value 10 for the y. And we got the output 15.

The second time the same function myFun is called with two arguments. The first value will be passed to x which is 5 and the second value will be 3 which will be copied to y. And accordingly, we will get 8 as output.

#include <iostream>
using namespace std; 

int myFun(int x, int y=10)
{
    return x+y; 
}

int main()
{
    int a=5; 
    int b=3; 
    int c; 
    int d; 

    c=myFun(a); 
    d=myFun(a,b); 
    cout<<"c: "<<c<<endl; 
    cout<<"d: "<<d<<endl; 

    return 0; 
}

OUTPUT

c: 15
d: 8

Key Points:

  • Default arguments are different from constant arguments as constant arguments can’t be changed whereas default arguments can be overwritten if required.
  • Default arguments are overwritten when calling function provides values for them. For example, calling of function sum(10, 15, 25, 30) overwrites the value of z and w to 25 and 30 respectively.
  • During calling of function, arguments from calling function to called function are copied from left to right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z. Therefore, the default value is used for w only.
  • Once default value is used for an argument in function definition, all subsequent arguments to it must have default value. It can also be stated as default arguments are assigned from right to left. For example, the following function definition is invalid as subsequent argument of default variable z is not default.

https://github.com/amitntrivedi/ObjectOrientedConceptsandProgramming/blob/master/Classes%20And%20Objects/DefaultArguments.cpp

Write Short notes on Default Arguments in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *