Default Arguments in C++ function

Hey guys,
Today we will be learning what default arguments in C++ function are and how they work
So read on…

What are Default Arguments?

Normally when we call a function, we pass a value i.e. parameters into the function. The C++ functions needs to know what kind of values are coming such as int or float and hence we define it beforehand in the function definition.

But what if while sending the values, we decide not to send one of the values?
We would end up with an error. To prevent this error, we initialize the parameters to a certain value where we are defining the parameters so that if the value does not come, it can use the initialized value. These initialized variables are default arguments.

It is not necessary to have default arguments but having it makes everything better.
Assume we have 4 parameters, we can have either 0 or 1 or 2 or 3 or all 4 initialized.
Out of those 4, none of them are initialized, we need to pass a value for every argument.

If 1 is initialized, we can call the function with minimum 3 arguments
Now if 2 are initialized, we can call the function with a minimum of 2 arguments
If we have 3 parameters initialized, we can call the function with a minimum of 1 argument.
And lastly, if all 4 are initialized, we can call the function with no argument at all.

Syntax:

<return_type> <function_name>(<datatype> <variable>=<value>, <datatype> <variable>)
{
    //code
}

Here the first parameter has a default argument but the second does not hence we need a minimum of 1 argument passed while calling the function.

Example:

int abc(int a=0, float b=0.0, int c)
{
    cout<<a+b+c;
}

As you can see, a and b are default arguments but c isn’t
So while calling the function, we don’t necessarily give a and b as arguments but we do need to give c

Code Sample:

Take a look at the following code:

#include <iostream>
using namespace std;

int multi(int a, int b=1, int c=2)
{
    cout<<a*b*c<<"\n";
}
int main()
{
    multi(5,10,20);  //parameter for a,b,c
    multi(5,10);     //parameter for a,b
    multi(5);        //parameter for a
}
  1. When we are passing 5,10,20,
    a gets 5
    b gets 10
    c gets 20
    Output is 5*10*20 i.e. 1000
  2. When we pass 5,10,
    a gets 5
    b gets 10
    c does not get a value so goes to its default value i.e. 2
    Hence the output is 5*10*2 i.e. 100
  3. When we pass 5,
    a gets 5
    b and c do not get a value so resort to their default value that is 1 and 2 respectively.
    Hence the output is 5*1*2 i.e. 10
  4. b and c have default arguments in the function call whereas a does not

Hence the output:

1000
100
10

 

That brings us to the end of this tutorial.
I hope you understood default arguments and were able to execute it by yourself.
If you have any more doubts, feel free to ask it in the comment section.

Also, read: Cascading Member Functions in C++

 

Leave a Reply