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(); }- A. 3 2 1
- B. 1 2 3
- C. 3 3 3
- 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
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- What is printed? java class Box<T> { private T value; void set(T v) { value = v; } T get() { return value; } } public class Main { public…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 200…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java class Base { void show() { System.out.print("Base"); } } class Sub extends Base { void show() {…
- What is printed? cpp struct Animal { virtual std::string sound() const = 0; void makeSound() const { cout << sound(); } virtual ~Animal()…