C++ default parameters: which function(s) cannot legally have default arguments?

Difficulty: Easy

Correct Answer: main()

Explanation:


Introduction / Context:
Default arguments in C++ let you omit trailing parameters at the call site. They are inserted by the compiler during overload resolution, which makes APIs more convenient while keeping type safety. However, not every function may carry default arguments. This item focuses on identifying the exception among common function categories: ordinary member functions of classes and structures versus the special program entry point, main().


Given Data / Assumptions:

  • C++ allows default arguments on ordinary functions and on member functions (both class and struct).
  • Default arguments must be specified in a declaration that is visible to all call sites (typically headers).
  • The function main() is a special entry point with an implementation-defined but fixed signature.


Concept / Approach:

The syntax rules for default arguments apply broadly: free functions, member functions, and even function-pointer parameters can use them. The single notable outlier is the program's entry point. main() must conform to one of the permitted signatures (commonly int main() or int main(int, char**)), and the standard does not allow you to modify that interface with defaulted parameters. By contrast, class and struct member functions are fully eligible for default arguments because, in C++, struct and class have identical member function rules (only the default access differs).


Step-by-Step Solution:

Check class member: allowed → eligible for defaults. Check struct member: same rules as class → eligible for defaults. Check main(): must match mandated signatures → defaults not allowed. Therefore, select main().


Verification / Alternative check:

Attempt to declare int main(int argc = 0, char** argv = nullptr). Compilers reject this because main()'s signature is constrained. Conversely, adding defaults to a member function like void f(int x = 1) compiles and works as expected.


Why Other Options Are Wrong:

Member function of class — permitted; defaults are common in class APIs.

Member function of structure — permitted; structs follow the same rules.

Both B and C — incorrect because C is allowed while B is not.


Common Pitfalls:

  • Believing struct members follow different language rules from class members.
  • Trying to place default arguments in multiple declarations, which is ill-formed.


Final Answer:

main()

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion