Computer Language/C++

[C++] Default Value of the Parameter

정우섭 2020. 5. 2. 16:42

The parameter in C++ can have default value.

 

Let's say there is a function like this.

 

1
2
3
4
int Func(int num1 = 1int num2 = 2)
{
    return num1 + num2;
}
 

 

'num1' and 'num2' have default value.

 

It means when the function is called without any factors passed, the default value will be used.

 

Func();           // num1 = 1, num2 = 2

Func(10);        // num1 = 10, num2 = 2

Func(20, 30);   // num1 = 20, num2 = 30

 

So these ways of calling function are available.

 

You can think of this as kind of a simple overloading.

 

But the point is that the passed factors always fill up the parameter from left to right.

 

 

1
2
3
4
int Func(int num1 = 1int num2 = 2int num3)
{
    return num1 + num2 + num3;
}
 

 

Let's think about this kind of a situation.

 

Func(10, 20);

 

It'll occur an error if the function is called with out the factor of num3.

 

The value of num3 is nowhere.

 

 

 

1
2
3
4
5
6
7
8
9
int Func(int num1 = 1int num2 = 2)
{
    return num1 + num2 + num3;
}
 
int Func(void)
{
    return 10;
}
 
 

 

When the function is overloaded like this.

 

If you call

 

Func();

 

The compiler have no idea to figure out which function you are calling and the error occurs.

 

So while declaring the default value of the parameter, be careful just two things.

 

  1. Fill the default value from left to right.
  2. Before overloading a function look over if the parameters have default value.

 

 

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍