quant
quant

Reputation: 23112

Best practice for default parameters of methods of derived classes

I know that the following works on VC++12, so it's what I've been doing:

class IBase
{
  virtual void Method(int param = 0) = 0; // default here
}

class Derived
{
  void Method(int param = 0); // default here
}

void Derived::Method(int param /*= 0*/) // no default here
{
  // do something
}

Does the standard, best practice, or experience recommend another way of doing this, or is it ok? Should the default only be in the interface class / the derived class, or both? And why?

Upvotes: 1

Views: 233

Answers (1)

UltraInstinct
UltraInstinct

Reputation: 44454

The best practice is to put the default arguments in the declaration (Header files), and in the source files -- forget about default parameter. The way you are doing it is correct. This is so that all the users of this function see the default parameter, and have an option of not providing one.

If you put the default argument in the definition, all other translation units that use the default argument (meaning dont provide one), will result in compile errors.

From the inheritance perspective, the default value is not retained. The default value that is used comes from the type of the pointer (either base, or derived) that is used to invoke the the function. So it really boils down to your use case.

Upvotes: 2

Related Questions