ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
void greet() { cout << "Base::greet "; }
};
struct Sub : Base {
void greet() { cout << "Sub::greet "; }
};
void show(Base &b) { b.greet(); }
int main() {
Sub s;
show(s);
}- A. Sub::greet
- B. Base::greet
- C. Compile-time error: greet() is ambiguous
- D. Undefined behaviour
Correct answer: B. Base::greet
Neither greet() is virtual, so Sub::greet merely hides Base::greet by name rather than overriding it; there is no dynamic dispatch at all. show(Base &b) statically binds b.greet() to Base::greet based purely on b's declared type, Base&, even though the actual object is a Sub.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { static void hello() { cout << "Base::hello "; } }; struct Derived : Base { static void hello() { cout…
- What is printed? java class Outer { static int x = 100; static class Nested { int x = 200; void show() { System.out.println(x + " " +…
- What is printed? cpp class Singleton { static Singleton instance; Singleton() { cout << "Created "; } public: static Singleton get() { if…
- What is printed? cpp struct Base { int level = 1; }; struct Mid : Base { int level = 2; }; struct Leaf : Mid { int level = 3; void show()…
- 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…