Overview
Default arguments allow you to assign default values to function parameters, enabling the function to be called with fewer arguments than it is declared with. If a parameter is not provided during the function call, its default value is used. This feature simplifies function calls and increases flexibility.
This program demonstrates the use of default arguments to calculate the volume of a rectangle using different combinations of provided and default parameters.
Source Code
#include<iostream.h>
#include<conio.h>
void volume(int l=10,int b=20,int h=15);
void volume(int l,int b,int h)
{
int vol;
vol=l*b*h;
cout<<"\n\nVOLUME OF RECTANGLE IS:\t"<<vol;
}
void main()
{
clrscr();
cout<<"\n\n When length, breadth, height are default arguments";
volume();
cout<<"\n\n When breadth, height are default arguments";
volume(90);
cout<<"\n\n When height is default argument";
volume(20,15);
cout<<"\n\n When No default arguments";
volume(20,20,10);
getch();
}
OUTPUT
When the program is executed, the following output is displayed:
When length, breadth, height are default arguments
VOLUME OF RECTANGLE IS: 3000
When breadth, height are default arguments
VOLUME OF RECTANGLE IS: 27000
When height is default argument
VOLUME OF RECTANGLE IS: 20000
When No default arguments
VOLUME OF RECTANGLE IS: 4000
Explanation
-
Default Arguments:
In the function prototype
void volume(int l = 10, int b = 20, int h = 15);
, default values are assigned tol
,b
, andh
. These defaults are used when arguments are not explicitly provided during the function call. -
Scenarios Demonstrated:
-
Case 1:
volume()
All three parameters (
l
,b
, andh
) use their default values:10
,20
, and15
.Volume = 10 × 20 × 15 = 3000
-
Case 2:
volume(90)
l
is overridden with90
, whileb
andh
use their default values:20
and15
.Volume = 90 × 20 × 15 = 27000
-
Case 3:
volume(20, 15)
l
andb
are overridden with20
and15
, whileh
uses its default value:15
.Volume = 20 × 15 × 15 = 20000
-
Case 4:
volume(20, 20, 10)
All arguments are explicitly provided, so no default values are used.
Volume = 20 × 20 × 10 = 4000
-
Case 1:
-
Flexibility:
The use of default arguments reduces the need for multiple function overloads, making the code more concise and easier to manage.
Key Notes
- Default arguments must be specified in the function declaration or prototype.
- Once a parameter is assigned a default value, all subsequent parameters must also have default values.
- This feature is particularly useful for functions with common parameters, reducing redundant calls.
EmoticonEmoticon