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(); }- A. BB
- B. XX
- C. Compile-time error: impl is not virtual
- 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
- What happens? cpp template <class T> T mx(T a, T b) { return a > b ? a : b; } int main() { cout << mx(3, 7); // L1 cout << mx(1, 2.5); //…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "a"; } }; struct B { B() { cout << "B"; } ~B() { cout << "b"; } }…
- Which line fails to compile? cpp string a = "a" + "b"; // L1 string b = string("a") + "b"; // L2 string c = "a" + string("b"); // L3…
- What is printed? cpp int main() { string s = "hi"; try { cout << s.at(1); s.at(5); cout << "X"; } catch (const outofrange&) { cout << "R"…
- What is printed? cpp int main() { map<string, int> m; if (m["x"] == 0) cout << m.size(); cout << m.count("y") << m.size(); }
- What is printed? cpp int main() { set<int, greater<int>> s{3, 1, 3, 2}; for (int x : s) cout << x; cout << s.size(); }