ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Complex {
    double re, im;
public:
    Complex(double r, double i) : re(r), im(i) {}
    Complex operator+(const Complex& o) const { return Complex(re + o.re, im + o.im); }
    friend ostream& operator<<(ostream& os, const Complex& c) { return os << c.re << "+" << c.im << "i"; }
};
int main() {
    Complex a(1, 2), b(3, 4);
    cout << (a + b);
}
  1. A. 4+6i
  2. B. Compilation error: operator+ must be a free function
  3. C. 1+2i3+4i
  4. D. Compilation error: operator<< cannot be a friend

Correct answer: A. 4+6i

operator+ is a member taking the other operand by reference, returning a new Complex(re+o.re, im+o.im) = Complex(4, 6). The friend operator<< then formats it as "4+6i" via the overloaded stream insertion.

More OOP with C++ and Java questions

Exams that ask this topic