Kevin217 Kevin217 - 1 month ago 10
C++ Question

c++ -- Confusion about using Default Argument

For example, there're 3 files,

sum.h
,
sum.cpp
, and
main.cpp
.

sum.h
--

...
int sum (int, int, int);
...


sum.cpp


...
int sum (int a, int b, int c=10) {
return a + b + c;
}


main.cpp


...
cout << sum (1, 2) << endl;
...


The compiler throws an error saying
too few arguments to function...
.

It works fine if I code as
cout << sum (1,2,3) << endl;

But how to just pass only 2 argument?

Answer

Default function arguments must go in the function declaration that the call site sees.

int sum (int, int, int = 10);

They are required at the expression where the function is called. The implementation shouldn't care if it is passed the default or not.

Furthermore, you can re-declare the function in a smaller scope, and give completely different default arguments. This code snippet is taken from the c++17 standard draft and demonstrates what I mean:

void f(int, int);
void f(int, int = 7);
void h() {
  f(3);                         // OK, calls f(3, 7)
  void f(int = 1, int);         // error: does not use default
                                // from surrounding scope
}
void m() {
  void f(int, int);             // has no defaults
  f(4);                         // error: wrong number of arguments
  void f(int, int = 5);         // OK
  f(4);                         // OK, calls f(4, 5);
  void f(int, int = 5);         // error: cannot redefine, even to
                                // same value
}
void n() {
  f(6);                         // OK, calls f(6, 7)
} 

Theoretically (don't do this in practice), you can even have different headers that declare the same function with a different default parameter value. And it will work as expected, so long as they aren't both included in the same translation unit.