ReviseAlgo Logo

Functions

Default Arguments

Parameters with default values

Interview: Function flexibility

Default Arguments

Default arguments allow callers to omit trailing arguments. The compiler substitutes the default values at the call site. This simplifies APIs by letting callers use sensible defaults without verbosity.

Rules for Default Arguments

  • Defaults must be specified from rightmost parameters leftward — you cannot skip a parameter.
  • Defaults are usually specified in the declaration (header), not the definition (source).
  • Each parameter can only have one default in the program — redeclaring different defaults is an error.

Interview Corner

Q: What is the difference between default arguments and overloading?

A: Default arguments create a single function where the compiler fills in missing values. Overloading creates distinct functions. Default arguments can't be used when different overloads need different implementations — just different parameter counts. Overloads provide more flexibility but more code. Default arguments are simpler for common patterns like optional configuration parameters.

Common Pitfalls

  • Defaults in definition instead of declaration: Adding defaults in the .cpp definition instead of the .h declaration means they're invisible to other translation units.
  • Virtual function defaults: Default arguments in virtual functions are resolved at compile time based on the static type, not dynamically. This can lead to unexpected behavior with polymorphism.

Best Practices

  • Always place default argument values in the header declaration, not the source definition.
  • Avoid default arguments on virtual functions to prevent surprising behavior in polymorphic hierarchies.