ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct Base {
    static void hello() { std::cout << "Base::hello"; }
};
struct Derived : Base {
    static void hello() { std::cout << "Derived::hello"; }
};
int main() {
    Base *p = new Derived();
    p->hello();
}
  1. A. Derived::hello
  2. B. Compilation error: cannot call static via pointer
  3. C. Both
  4. D. Base::hello

Correct answer: D. Base::hello

Static member functions are never virtual, even if called through a pointer with -> syntax; the call is resolved at compile time purely from the pointer's STATIC type (Base*), so Base::hello() is called regardless of the pointed-to object's dynamic type.

More OOP with C++ and Java questions

Exams that ask this topic