Table of contents | |
Introduction | |
Syntax | |
Advantages | |
Disadvantages | |
Conclusion |
In C++, a function argument can be given a default value, which means that if the caller doesn't provide a value for that argument, the default value will be used. This feature is called "default arguments." Default arguments are useful when you want to provide a default behavior for a function, but still allow the caller to override it if necessary.
The syntax for default arguments in C++ is as follows:
return_type function_name(parameter1=default_value1, parameter2=default_value2, ..., parameterN=default_valueN)
{
// Function body
}
Explanation
Example:
#include <iostream>
void print(int a, int b=10, int c=20)
{
std::cout << "a=" << a << ", b=" << b << ", c=" << c << std::endl;
}
int main()
{
print(1); // Output: a=1, b=10, c=20
print(2, 30); // Output: a=2, b=30, c=20
print(3, 40, 50); // Output: a=3, b=40, c=50
return 0;
}
Explanation
Default arguments provide the following advantages:
Default arguments have some limitations:
Sample Problems:
1. Write a C++ function that calculates the volume of a cube with default edge length of 1 unit.
#include <iostream>
double cubeVolume(double edge=1.0)
{
return edge * edge * edge;
}
int main()
{
std::cout << "Volume of a cube with edge length 2 units: " << cubeVolume(2.0) << std::endl;
std::cout << "Volume of a cube with default edge length: " << cubeVolume() << std::endl;
return 0;
}
Volume of a cube with edge length 2 units: 8
Volume of a cube with default edge length: 1
Explanation: In this example, we define a function 'cubeVolume' that takes one double parameter, `edge2. Write a C++ function that calculates the factorial of a given number with a default argument of 1.
#include <iostream>
int factorial(int n, int result=1)
{
if (n == 0 || n == 1)
{
return result;
}
else
{
return factorial(n-1, result*n);
}
}
int main()
{
std::cout << "Factorial of 5: " << factorial(5) << std::endl;
std::cout << "Factorial of 6 with initial value of 10: " << factorial(6, 10) << std::endl;
return 0;
}
Factorial of 5: 120
Factorial of 6 with initial value of 10: 7200
Explanation
Default arguments are a powerful feature of C++ that can simplify the function call and provide default behavior for the function. They have some limitations, but they are generally useful and widely used in C++ programming.
70 videos|45 docs|15 tests
|
|
Explore Courses for Software Development exam
|