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);
}- A. 500
- B. 300
- C. Compilation error: maxVal<Money> requires operator< not operator>
- 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
- What is printed? cpp class Shape { public: virtual void draw() const = 0; }; class Group : public Shape { vector<Shape> children; public…
- What is printed? java class Base { public int hashCode() { return 1; } } class Derived extends Base { @Override public int hashCode() {…
- What is printed? java class Base { Base self() { return this; } } class Derived extends Base { @Override Derived self() { return this; }…
- What is printed? java class Account { private double balance; Account(double b) { balance = b; } void withdraw(double amt) { if (amt >…
- What is printed? java class Task { void execute() throws Exception { try { riskyStep(); } catch (RuntimeException e) { throw new…
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…