ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct A {
    A() { }
    A(const A&) { cout << "C"; }
    A& operator=(const A&) { cout << "="; return *this; }
};
void f(A a) { }
void g(const A& a) { }
int main() {
    A x;
    A y = x;
    A z(y);
    z = x;
    f(x);
    g(x);
    A w;
    w = y = z;
}
  1. A. CC=CC==
  2. B. C==C==
  3. C. CC=C==
  4. D. CC=C=

Correct answer: C. CC=C==

A y = x creates a new object, so it is copy initialisation and calls the copy constructor, as does A z(y). z = x assigns to an existing object: operator=. Passing x by value to f copies it (C); passing by const reference to g copies nothing. w = y = z is two assignments, right to left. The '=' sign in a declaration never calls operator=.

More OOP with C++ and Java questions

Exams that ask this topic