Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default arguments in definition or declaration?

Tags:

c++

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?
{

}
like image 385
nonsensation Avatar asked Oct 27 '25 20:10

nonsensation


2 Answers

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.

like image 151
Cheers and hth. - Alf Avatar answered Oct 30 '25 10:10

Cheers and hth. - Alf


do it here

class Test
{
    void method( bool flag /* = true */ ); // here?
};

to keep the overview and make your life easier.

like image 38
deW1 Avatar answered Oct 30 '25 10:10

deW1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!