Monday, June 16, 2008

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 arguments

void myfunc(int a, bool flag = true) {

    if ( flag == true ) {

       // Do something
       cout << "Flag is true. a = " << a << endl;
    else {

       // Do something
       cout << "Flag is false. a = " << a << endl;

int main()

    myfunc(200, false);

    return 0;

Flag is true. a = 100
Flag is false. a = 200


Post a Comment

Contact Form


Email *

Message *

Back to Top