C++ default parameters and base-class constructor: what does this program print when calling CountIt with two arguments?\n\n#include<iostream.h>\nclass BaseCounter\n{\nprotected:\n long int count;\npublic:\n void CountIt(int x, int y = 10, int z = 20)\n {\n count = 0;\n cout << x << " " << y << " " << z << endl;\n }\n BaseCounter() { count = 0; }\n BaseCounter(int x) { count = x; }\n};\nclass DerivedCounter : public BaseCounter\n{\npublic:\n DerivedCounter() { }\n DerivedCounter(int x) : BaseCounter(x) { }\n};\nint main()\n{\n DerivedCounter objDC(30);\n objDC.CountIt(40, 50);\n return 0;\n}

Difficulty: Easy

Correct Answer: 40 50 20

Explanation:


Introduction / Context:
This program exercises default parameters in a member function inherited by a derived class. The call supplies two explicit arguments; the third uses the default specified in the function declaration.


Given Data / Assumptions:

  • DerivedCounter objDC(30) initializes the base part but does not affect CountIt’s parameter printing.
  • Call is objDC.CountIt(40, 50).
  • Defaults for CountIt are y = 10, z = 20.


Concept / Approach:
Default arguments are filled from right to left for parameters not provided at the call site. With two arguments, x = 40 and y = 50 are bound explicitly; z uses its default 20. The body assigns count = 0 and prints the three values.


Step-by-Step Solution:
1) x binds to 40. 2) y binds to 50. 3) z falls back to 20. 4) The function prints “40 50 20”.


Verification / Alternative check:
Call CountIt(40) and you would see “40 10 20” because both y and z would use defaults.


Why Other Options Are Wrong:
Options involving 30 confuse the stored count with parameters; “Garbage” is irrelevant because all parameters are fully specified or defaulted.


Common Pitfalls:
Assuming constructor arguments propagate into unrelated function parameters.


Final Answer:
40 50 20

More Questions from Functions

Discussion & Comments

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