C++ Default Arguments

What are default arguments in C++?

  • Default argument is a value given in the function declaration. The compiler automatically inserts this if a value is not provided during the function call.
  • Default arguments are similar to function overloading in the sense that both features allow to use a single function name in different scenarios.
  • The guideline to follow default arguments vs function overloading. When the desired behavior is almost similar it is recommended to use default arguments and when the behavior is different function overloading.
  • Only trailing arguments can be defaulted. Once a particular arguments is made default all the following arguments should also be made default.
  • Default arguments are useful in cases where capability of an existing function is increased by adding a new argument. Existing function calls need not be changed for this.

Demonstrate the usage of default arguments

#include <iostream>using namespace std;// Function with default argumentsvoid myfunc(int a, bool flag = true) {if ( flag == true ) {// Do somethingcout << "Flag is true. a = " << a << endl;}else {// Do somethingcout << "Flag is false. a = " << a << endl;}}int main(){myfunc(100);myfunc(200, false);return 0;}OUTPUT:-Flag is true. a = 100Flag is false. a = 200