Reputation: 160
so why is it not allowed to have default arguments on the function declaration and implementation? Wouldnt this be more readable for the implementer and the user of the function?
Is there a special reason why this is not allowed, or why the compiler or linker cant handle this?
Best regards
Upvotes: 1
Views: 1773
Reputation: 114461
There is no real reason except that the committee decided so and they apparently like to show their power by torturing millions of programmers this way.
Ok... may be this is not true but in my opinion it's a more logical explanation of why this is forbidden that anything I've read about the issue.
Note that g++
with -fpermissive
allows default to be specified both in declaration and in implementation IF THE VALUES ARE THE SAME and gives an error if they are different.
This is the way IMO it should be in the standard, but it's not.
Because no.
PS: Don'y try to read too much into logical reasons about the rules of C++. Many times there are reasons, sometimes there are just poor justifications of a sad incident that must stay in forever for backward compatibility, sometimes there is no reason at all... it's just the way it is. This, added to the complexity of C++ and the concept of Undefined Behavior, is in my opinion why experimenting with C++ doesn't work well and you need to actually read the standard rules. Being smart doesn't help if you're experimenting, because the "correct" answer is often the wrong one. There's no way you can guess what was the decision taken in that rainy day at the committee meeting.
Upvotes: 0
Reputation: 217135
In fact, it is just that we cannot have, in the same scope, 2 declarations with a (common parameter with a) default argument:
void foo(int = 42);
void foo(int = 42); // Error.
and definition acts also as declaration.
if your definition doesn't include the header with the declaration, you might have default in definition too.
Notice that default
is not part of the signature, but should anyway is the same (by scope) for each translation unit (for inline functions, and also for non-inline functions since C++20 (but some default can be omitted)).
I don't know the why of those rules though.
Upvotes: 3