Default Arguments
A parameter can be assigned a default value to be assumed by the corresponding
argument when the latter is not specified.
ClassA(int x = 10) // x defaults to 10
If only a few parameters of a function have default values, in the function
declaration such parameters must appear to the right of those that do not
default to any value.
void func(int x, char y, int z = 14, double d = 21.4);
Only the arguments corresponding to
z and
d in the code above could be omitted.
Example
#include <iostream>
using namespace std;
class ClassA
{
int a;
public:
ClassA(int x = 10) // x defaults to 10
{
a = x;
}
void seta(int y)
{
a = y;
}
int geta()
{
return a;
}
};
int main()
{
ClassA obj1; // the argument defaults to 10
cout << obj1.geta() << endl;
ClassA obj2(21); // the argument here is specified
cout << obj2.geta() << endl;
}
Output
10
21