ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base { int level = 1; };
struct Mid : Base { int level = 2; };
struct Leaf : Mid { int level = 3; void show() { cout << level << " " << Mid::level << " " << Base::level; } };
int main() { Leaf l; l.show(); }
  1. A. 3 2 1
  2. B. 1 2 3
  3. C. 3 3 3
  4. D. Compile-time error: level is ambiguous

Correct answer: A. 3 2 1

Each class in the hierarchy has its own distinct level member (they are not overridden, just separately named-and-shadowed). Plain level inside Leaf's own scope finds Leaf's own level (3). Explicitly qualifying with Mid:: or Base:: reaches into those specific base subobjects' own members, 2 and 1 respectively.

More OOP with C++ and Java questions

Exams that ask this topic