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();
}
  1. A. Derived::hello
  2. B. Base::hello
  3. C. Compile-time error: static member functions cannot be called via a pointer
  4. 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

Exams that ask this topic