C++ (inheritance, default arguments, and overrides) — track member initialization and outputs with pre/post operators.
#include
class CuriousTabBase {
public:
int x, y;
CuriousTabBase(int xx = 0, int yy = 5) { x = ++xx; y = --yy; }
void Display() { cout << --y; }
~CuriousTabBase() {}
};
class CuriousTabDerived : public CuriousTabBase {
public:
void Increment() { y++; }
void Display() { cout << --y; }
};
int main(){
CuriousTabDerived objCuriousTab; // uses base default ctor
objCuriousTab.Increment();
objCuriousTab.Display();
return 0;
}
What is printed?
-
A3
-
B4
-
C5
-
DGarbage-value
-
EThe program will report compile time error.
Answer
Correct Answer: 4
Explanation
Introduction / Context:This question tests default argument handling in a base constructor and how pre/post operators affect state across member functions, including an override of Display() in the derived class.
Given Data / Assumptions:
- Base constructor runs with defaults xx = 0, yy = 5.
- In constructor: x = ++xx → 1; y = --yy → 4.
- Derived adds Increment() → y++.
- Derived overrides Display() to print --y.
Concept / Approach:Trace the member y across operations in order: initialization, increment, and pre-decrement during display. The code never uses the base Display(); it uses the override in the derived type, operating on the same y member inherited from the base.
Step-by-Step Solution:
1) After construction: y = 4.2) Call Increment(): y becomes 5.3) Call Display(): pre-decrement prints 4 and sets y = 4.Verification / Alternative check:If you instead called the base Display() (e.g., objCuriousTab.CuriousTabBase::Display()), the same calculation would occur since both versions print --y.
Why Other Options Are Wrong:
- 3 or 5: Off-by-one due to misreading pre/post semantics.
- Garbage/compile error: All members are initialized and types valid.
Common Pitfalls:Forgetting that ++ and -- change the stored value, not just the printed value.
Final Answer:4