Reputation: 14413
At my workplace, usually default parameters are specified in the declaration.What is the normal custom? Should I specify default parameters in method declaration or method definition?
EDIT: Is there any way to specify default parameters for references?
EDIT: Can someone please provide an example of default arguments for reference parameters?
Upvotes: 1
Views: 419
Reputation: 2947
I used to make use of default values, but meanwhile I changed my mind: I find the code better readable when I write the parameter values explictly. Sometimes I define another method like the following:
bool Initialize( const char * pszPath );
bool InitializeDefault();
instead of
bool Initialize( const char * pszOptPath = NULL );
Upvotes: 0
Reputation: 320391
Well, the normal practice is to have the same set of default arguments for all translation units. In order to achieve that you obviously have to specify the default arguments in the declaration of the function in the header file.
As for default argument of reference parameter... of course, it is possible. For example
extern int i;
void foo(int &r = i);
void bar(const double &r = 0);
Upvotes: 1
Reputation: 3247
Must be at method declaration, so that the caller can know what is exactly expected by the function.
You can do tricks like Alf says but not sure why is it needed. May be you want to take a look at your design of function.
Upvotes: 0
Reputation: 145239
ybungalobill has already answered the question about where.
Regarding references, for a reference to const
T you can just specify a default value directly.
For a reference to non-const
you need to specify the default "value" as a reference to non-const
. This might be a global, or an instance of a class with suitable conversion. E.g.,
#include <iostream>
struct DummyInt
{
int dummy;
operator int& () { return dummy; }
DummyInt(): dummy( 0 ) {}
};
void foo( int& v = DummyInt() ) {} // Whatever
int main()
{
int x = 42;
foo( x );
foo();
}
Cheers & hth.,
– Alf
Upvotes: 2
Reputation: 72469
Method declaration. The caller probably doesn't have the definition, but default parameters must be known at the call place.
Upvotes: 7