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 this:
void displayNumPower(int num, int pow);
Normally, we have to pass both arguments if we want to call or invoke above function without any error.
If you want to omit the pow argument and display the square of passed value in num argument then you have to use default arguments.
In above scenario, we have to assign 2 to that pow argument during function declaration.
After adding the default argument, our function will look like this:
void displayNumPower(int num, int pow = 2);
Now, even if we do not pass the second argument i.e. 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 the use of Default Arguments in Function Overloading
- Declare a class Number which has two member functions named displayNum() but with different function signature.
- First member function named displayNum(int n), simply accepts an integer type value.
- Second member function accepts floating type value but it also has a default value 0.0 assigned to it.
- In the main() function, create an instance of class Number and simoly call the displayNum() function 3 times.
- 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<<"\n\nNumber: " << n << endl;
}
void displayNum(float n = 0.0)
{
cout<<"\n\nNumber: " << n << endl;
}
};
// NOTE: Some compilers may not support clrscr() and getch() functions. In that case, comment them.
int main()
{
clrscr();
Number nObj;
nObj.displayNum(2); // Invokes the method which accepts integer argument.
nObj.displayNum(2.2f); // Invokes the method which accepts float argument.
nObj.displayNum(); // Invokes the method which accepts float argument but default argument value will be assigned.
getch();
return 0;
}
Output 😃
On execution of above code, the output of the program will be displayed as:
Number: 2
Number: 2.2
Number: 0
In first function call, the displayNum(int n) will be invoked whereas displayNum(float n = 0.0) will be invoked in second function call.
Since, there is no value passed in the third function call, displayNum(float n = 0.0) will be invoked and the default value 0 will be assigned to the variable n.
Comments