ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
template<typename T>
T maxVal(T a, T b) { return a > b ? a : b; }
class Money {
    int cents;
public:
    Money(int c) : cents(c) {}
    bool operator>(const Money& o) const { return cents > o.cents; }
    friend ostream& operator<<(ostream& os, const Money& m) { return os << m.cents; }
};
int main() {
    Money a(500), b(300);
    cout << maxVal(a, b);
}
  1. A. 500
  2. B. 300
  3. C. Compilation error: maxVal<Money> requires operator< not operator>
  4. D. Compilation error: Money needs a copy constructor

Correct answer: A. 500

maxVal is a template that works with any type supporting operator>; Money provides it, so maxVal<Money>(a, b) compiles and compares cents (500 > 300), returning a, which prints as 500 via the overloaded operator<<.

More OOP with C++ and Java questions

Exams that ask this topic