ProgrammingModerateProduct-company interview pattern

What is printed?

What is printed?
class A {
public:
    int x;
    A(int v) : x(v) {}
};
int main() {
    A a(5);
    A b = a;
    b.x = 9;
    cout << a.x << b.x;
}
  1. A. 99
  2. B. 59
  3. C. 55
  4. D. 95

Correct answer: B. 59

A b = a copies the object (memberwise, by the implicit copy constructor); b is independent of a. Changing b.x leaves a.x at 5. 99 is what Java-style reference semantics would give, but C++ objects are values.

More OOP with C++ and Java questions

Exams that ask this topic