Some terminology: This
void myFunction(string something, int w);
is a declaration. This
void myFunction(string something, int w) {
// note the function body
}
is usually called a definition. But it’s really both, a definition as well as a declaration. For simplicity I’ll keep calling it the definition.
Your problem is that order matters, specifically the order in which you declare, define and call your function. At the call site in main()
the only visible declaration of myFunction
takes a string and an integer and has no default arguments. The definition is not visible at that point, so it doesn’t come into play at all. For the compiler it looks like you attempt to call a function that doesn’t exist.
There are two solutions:
- Move the default argument from the definition to the declaration. That’s the common way to do it. In most cases you have the declaration (including any default arguments) in a header file and a matching definition (without the default arguments) in a cpp file that #includes the header.
- Get rid of the declaration and move the definition above
main()
. This works because the definition is also a declaration.
In this simple example both are equally valid.
For the definition default arguments are irrelevant. It doesn’t matter if you get the 5
because someone typed it explicitely at the call site or if the compiler added it via the default argument. That’s why, when you have a separate declaration and definition, the default argument is only necessary for the declaration. You can and should leave it out of the definition. Otherwise you have to maintain it in two places for no good reason.
int w=5
in the declaration not the definition.