ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
template <class T> struct Base {
    void hi()   { static_cast<T*>(this)->impl(); }
    void impl() { cout << "B"; }
};
struct X : Base<X> { void impl() { cout << "X"; } };
struct Y : Base<Y> { };
int main() { X x; Y y; x.hi(); y.hi(); }
  1. A. BB
  2. B. XX
  3. C. Compile-time error: impl is not virtual
  4. D. XB

Correct answer: D. XB

This is the CRTP (static polymorphism): Base<T> casts this to the derived type and calls impl() resolved at compile time. X provides its own impl; Y only inherits Base's, so it prints B. No virtual functions are involved.

More OOP with C++ and Java questions

Exams that ask this topic