ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Base {
static void hello() { cout << "Base::hello "; }
};
struct Derived : Base {
static void hello() { cout << "Derived::hello "; }
};
int main() {
Base *p = new Derived();
p->hello();
}- A. Derived::hello
- B. Base::hello
- C. Compile-time error: static member functions cannot be called via a pointer
- D. Compile-time error: hello() is redeclared with a conflicting signature
Correct answer: B. Base::hello
Static member functions in C++ are never virtual and are resolved purely by the static type used to call them. Even though p actually points at a Derived, p->hello() is compiled as a call to Base::hello(), since p's declared type is Base*. (Calling a static method through -> on a pointer is legal syntax, just resolved statically.)
More OOP with C++ and Java questions
- 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…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 200…