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

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