ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
template <typename T>
T maxVal(T a, T b) { return a > b ? a : b; }
int main() {
cout << maxVal(3, 7) << " " << maxVal(2.5, 1.5) << " " << maxVal<std::string>("a", "b");
}- A. 7 2.5 b
- B. Compile-time error: maxVal cannot be used with both numeric and string types
- C. 3 1.5 a
- D. 7 1.5 b
Correct answer: A. 7 2.5 b
Templates are instantiated separately for each distinct type used: maxVal<int>(3,7) compares ints (7 wins), maxVal<double>(2.5,1.5) compares doubles (2.5 wins), and the explicitly specified maxVal<std::string>("a","b") compares strings lexicographically ("b" wins). No single generic function is shared across types the way Java's erasure works — each instantiation is its own compiled function.
More OOP with C++ and Java questions
- What happens? java interface A { default String id() { return "A"; } } interface B { default String id() { return "B"; } } class D…
- What is printed? cpp struct Base { virtual void f() = 0; void greet() { cout << "greet "; f(); } }; struct Derived : Base { void f()…
- What happens? cpp struct Shape { virtual double area() const = 0; }; int main() { Shape s; cout << s.area(); }
- What is printed? java abstract class Vehicle { abstract void move(); void start() { System.out.print("starting "); move(); } } // in main…
- What is printed? cpp class Base { public: Base(int x) { cout << "Base(" << x << ") "; } }; class Derived : public Base { public: Derived()…
- What is printed? java class Outer { static class Nested { void show() { System.out.print("Nested.show"); } } } // in main: Outer.Nested n…