Default Argument in C++
Here is the implementation of the default argument in C++:
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;
// A function with default arguments,
// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}
// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output
25 50 80
Default Arguments and Function Overloading in C++:
Function overloading is a common practice in languages such as C++. There are some rules and restrictions when using preset parameters in function overloading:
- Consistency: Overloaded functions must have a clear and specific purpose. Default parameters should not cause ambiguity in the calls.
- Parameter positioning: To avoid confusion/misunderstanding during function calls, default arguments in a function declaration must come after all non-default parameters.
- Ambiguity in function calls: Sometimes combining overload with presets can be confusing. For example, if there are many overloaded functions with preset parameters, the compiler will have difficulty deciding which overloaded function to call.
In C++, consider the following overloaded functions:
#include <iostream>
using namespace std;
void printMessage(int count, string message = "Hello");
void printMessage(int count, bool includeTimestamp = false);
int main() { printMessage(5); }
The parameter lists for both functions are similar and they share the same name “printMessage”. If you call printMessage(5) with just one integer argument, there might be ambiguity about which function to use.
You must make sure that the parameter types and order of each overloaded function are unique in order to resolve ambiguity.
Default Argument in Programming
Default arguments are one of the powerful features in programming that allows developers to specify a default value for one or more parameters in a function and provides flexibility as it enables functions to be called with different numbers of arguments. When calling a function, the programmer can omit some of the arguments for parameters that have default values, and the function will use those default values instead which makes functions more versatile and user-friendly. Languages like C++, Python, etc. allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.
Table of Content
- What are Default Arguments?
- Syntax of Default Argument
- Default Argument in C++
- Default Argument in Python
- Default Argument in Javascript
- Default Argument in Java
- Advantages of Default Argument
- Disadvantages of Default Argument