Write a C++ program to demonstrate the use of default arguments in function overloading.

As per the program definition, we have to demonstrate the use of default arguments that too with function overloading.

What are Default Arguments in C++? πŸ€”

Suppose you want to declare a function which takes two arguments, one is the number and another one is power.

For example, the signature of the function looks something like:

void displayNumPower(int num, int pow);

Normally, we have to pass both arguments if we want to call above function without any error.

If you want to omit the pow argument and display the square of value passed in num argument then you have to use default arguments.

In above case, we have to assign a value (2) to that pow argument during function declaration.

After adding the default argument, our function will look like:

void displayNumPower(int num, int pow = 2);

Now, even if we don’t pass the value of pow, the default value 2 will be used in the function definition. πŸ˜‰

Tutorial πŸ“Ί

Watch the tutorial to understand how to solve this problem. πŸ˜‡

Steps πŸͺœ

To demo Default Arguments in Function Overloading

  1. Declare a class Number which has two member functions named displayNum but with different function signature.
  2. First member function named displayNum(int n), simply accepts an integer type value.
  3. Second member function accepts floating-point type value but it also has a default value 0.0 assigned to it.
  4. In main() function, create an instance of class Number and simply call the displayNum() function 3 times.
  5. Two function calls with integer and floating point type of values but do not pass any value in the last function call and see the difference.

Code πŸ’»

#include <iostream.h>
#include <conio.h>

class Number
{
  public:
    void displayNum(int n)
    {
      cout<<"\nNumber: " << n << endl;
    }
  
    void displayNum(float n = 0.0)
    {
      cout<<"\nNumber: " << n << endl;
    }
};

// NOTE: Some compilers may not support clrscr() and getch() functions. 
// In that case, comment them.

int main()
{
  clrscr();
  Number nObj;
  // Invokes the method which accepts integer argument.
  nObj.displayNum(2);
  // Invokes the method which accepts float argument.
  nObj.displayNum(2.2f);
  /* 
    Invokes the method which accepts float argument but default argument
    value will be assigned.
  */
  nObj.displayNum();
  getch();
  return 0;
}

Output 😍

In above code, the output of the program will be displayed as:

Number: 2

Number: 2.2

Number: 0

In 1st function call, the displayNum(int n) will be called and displayNum(float n = 0.0) will be invoked in 2nd function call.

Since there is no value passed in the 3rd function call, displayNum(float n = 0.0) will be invoked and the default value 0 will be assigned to the variable n.

This is how we can use the default arguments in function overloading in C++.
For more C++ Programs, click here.


Categorized in: