Write a C++ program to demonstrate the use of default arguments in 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
- 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-point type value but it also has a default value 0.0 assigned to it.
- In main() function, create an instance of class Number and simply 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<<"\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 😍
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.
Comments