CPA-21-02 practice question 16 of 35

What happens when you attempt to compile and run the following code? #include #include using namespace std; class complex{ double re, im; public: complex() : re(1),im(0.4) {} complex operator?(complex &t); void Print() { cout

Full set: 257 questions
Answer options
A: It prints: 1 0.4
B: It prints: 2 0.8
C: It prints: 0 0 Correct answer
D: It prints: 1 0.8
Correct Answer:
C. It prints: 0 0
Explanation

The provided code contains OCR artifacts where the minus operator - is replaced by ? and the arrow operator -> by ?>. C++ strictly prohibits overloading the ternary operator ?. Assuming the intended operators are - and ->, the operator- subtracts the re and im members of t from this. Both c1 and c2 are default-constructed to re=1, im=0.4. Subtracting c2 from c1 yields re=0, im=0.

Why Incorrect

A: This would be the output if c3 was assigned c1 directly without any subtraction. B: This would be the output if the overloaded operator performed addition instead of subtraction. D: This output does not correspond to any valid arithmetic operation on the given objects.

References

- ISO/IEC 14882:2014 (C++14 Standard), Section 13.5 [over.oper], Paragraph 3 (Operators that cannot be overloaded).

- Bjarne Stroustrup, "The C++ Programming Language, 4th Edition", Chapter 18.2.1 (Operator Overloading).

Scroll to Top