Should the default arguments of a function/method reside in the definition or in the declaration? What is the best practice here and why?
class Test
{
    void method( bool flag /* = true */ ); // here?
};
void Test::method( bool flag /* = true */ ) // or here?
{
}
Uhm, I don't have time to give a proper answer, but noting that C++ §8.3.6/6 says
” Default arguments for a member function of a class template shall be specified on the initial declaration of the member function within the class template
if one wants a single convention that works also for non-template code, one should better place defaults in the first declaration.
That's also generally most practical for readability.
For non-template code you can steadily add defaulting in subsequent redeclarations of a function, but it must be possible to omit actual arguments for all arguments to the right. Essentially that means decreasing the number of not-yet defaulted arguments. I fail to see the practical utility in this, or any rationale, and I've never seen it done in practice.
Anyway, regarding your statement in a comment “or in the definition as if it change you dont have to recompile the header”, note that a default value must be visible to the compiler at the place where the function is called.
do it here
class Test
{
    void method( bool flag /* = true */ ); // here?
};
to keep the overview and make your life easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With