C++ (name qualification in multiple-base-like contexts) — evaluate the printed sum after calling the specifically qualified BaseTwo::Display.
#include
static double gDouble; static float gFloat; static double gChar; static double gSum = 0;
class BaseOne { public: void Display(double x = 0.0, float y = 0.0, char z = 'A') {
gDouble = x; gFloat = y; gChar = int(z); gSum = gDouble + gFloat + gChar; cout << gSum; } };
class BaseTwo { public: void Display(int x = 1, float y = 0.0, char z = 'A') {
gDouble = x; gFloat = y; gChar = int(z); gSum = gDouble + gFloat + gChar; cout << gSum; } };
class Derived : public BaseOne, public BaseTwo { void Show() { cout << gSum; } };
int main() {
Derived objDev;
objDev.BaseTwo::Display(10, 20, 'Z');
return 0;
}
What value is printed?
-
AThe program will print the output 0.
-
BThe program will print the output 120.
-
CThe program will report run-time error.
-
DThe program will report compile-time error.
-
EThe program will print the output garbage value.
Answer
Correct Answer: The program will print the output 120.
Explanation
Introduction / Context:This question reinforces qualified calls to resolve ambiguity in multiply-inherited interfaces and shows how arguments flow into a function with defaults overridden at the call-site. The output is a straightforward arithmetic sum of three values stored in globals.
Given Data / Assumptions:
- We explicitly call
objDev.BaseTwo::Display(10, 20, 'Z'). - Inside
BaseTwo::Display, the globals are set andgSumis computed as the sum of the three converted values. 'Z'has integer code 90.
Concept / Approach:The computation uses gDouble = 10, gFloat = 20.0f, gChar = 90, so the sum is 10 + 20 + 90. The function itself streams that sum via cout, so the visible output is the numeric result.
Step-by-Step Solution:
Assign inputs: 10, 20, 'Z'.Convert and store: 10.0, 20.0f, 90.0.Compute: gSum = 10 + 20 + 90 = 120.Print gSum.Verification / Alternative check:Calling BaseOne::Display(10.0, 20.0f, 'Z') would compute the same numeric sum since the same values are used after conversions.
Why Other Options Are Wrong:
- 0 / garbage: contradicts the explicit arithmetic.
- Errors: The qualified call resolves any ambiguity; the code compiles and runs.
Common Pitfalls:Forgetting to qualify the call in multiple inheritance, which would make the call ambiguous and fail to compile.
Final Answer:The program will print the output 120.