ProgrammingHardProduct-company placement · GATE CS
Which lines fail to compile?
Which lines fail to compile?
struct M {
int v;
M(int x) : v(x) { }
M operator+(const M& o) const { return M(v + o.v); }
};
int main() {
M a(1);
M b = a + 2; // L1
M c = 2 + a; // L2
M d = a + a; // L3
}- A. L1 only
- B. L2 only
- C. L1 and L2
- D. None
Correct answer: B. L2 only
For a member operator the left operand must already be an M; implicit conversions apply only to the argument. So a + 2 converts 2 through M(int), but 2 + a finds no operator. Writing operator+ as a non-member friend makes both work.
More OOP with C++ and Java questions
- Why does the C++ standard reject a copy constructor declared as T(T other) for a class T?
- A drawing program uses the Visitor pattern: Shape has accept(Visitor v), and Circle implements it as v.visit(this). Visitor has overloads…
- How many of these statements about Java (9 or later) are correct? 1. An interface can declare instance fields. 2. An abstract class can…
- A UI component registers itself as an observer of a long-lived global EventBus when it is created but never unregisters. Screens using…
- A vending machine object behaves differently when Idle, HasCoin or Dispensing, and each state object decides which state comes next. A…
- Account.withdraw(amount) works for any amount up to the balance. A subclass FixedDeposit overrides it to throw an exception unless the…