ProgrammingHardTCS NQT · Infosys interview pattern

What is printed?

What is printed?
struct A {
    A()                     { cout << "D"; }
    A(const A&)             { cout << "C"; }
    A& operator=(const A&)  { cout << "="; return *this; }
};
int main() {
    A a;
    A b = a;
    A c;
    c = a;
}
  1. A. D=D=
  2. B. DCDC
  3. C. DCD=
  4. D. DDD=

Correct answer: C. DCD=

A b = a initialises a new object, so it calls the copy constructor (C), despite the = sign. c = a assigns to an already constructed object, so it calls operator= (=). Output: D, C, D, =.

More OOP with C++ and Java questions

Exams that ask this topic