ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Account {
    double balance = 0;
    friend void deposit(Account& a, double amt);
public:
    double getBalance() const { return balance; }
};
void deposit(Account& a, double amt) { a.balance += amt; }
int main() {
    Account acc;
    deposit(acc, 50.0);
    cout << acc.getBalance();
}
  1. A. 50
  2. B. Compilation error: deposit cannot access private member balance
  3. C. 0
  4. D. Compilation error: friend functions must be member functions

Correct answer: A. 50

deposit is declared a friend of Account, which grants it access to Account's private members (balance) despite being a free (non-member) function; it legally mutates balance, and getBalance() then reports 50.

More OOP with C++ and Java questions

Exams that ask this topic