Question 9
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
class Account {
protected:
int balance_ = 100;
};
class Savings : public Account {
public:
void transfer_from(Savings& other, int amt) {
if (amt > other.balance_) return;
other.balance_ -= amt;
balance_ += amt;
}
int balance() const { return balance_; }
};
int main() {
Savings a, b;
a.transfer_from(b, 60);
a.transfer_from(b, 60);
std::cout << a.balance() << ' ' << b.balance() << '\n';
return 0;
}
- A 160 40 Correct
- B 220 -20
- C 100 100
- D Compilation error
Correct Answer: Option A
Savings may access balance_ of another Savings object (its own type). The second transfer is refused because b has only 40 left.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!