ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Account {
    double balance;
public:
    Account(double b) : balance(b) {}
    Account operator+(const Account &other) const {
        return Account(balance + other.balance);
    }
    double get() const { return balance; }
};
int main() {
    Account a(100), b(50);
    Account c = a + b;
    cout << c.get();
}
  1. A. 100
  2. B. 50
  3. C. 150
  4. D. Compile-time error: operator+ must be a free function, not a member

Correct answer: C. 150

operator+ is declared as a member function taking one parameter (the right-hand operand); a + b calls a.operator+(b), which is perfectly legal — binary operators may be overloaded either as members (with the left operand as the implicit *this) or as free functions. It returns a new Account with balance 100+50=150.

More OOP with C++ and Java questions

Exams that ask this topic