C++ operator overloading for a 2D point: compute the result of Point operator+(Point) with default and explicit constructors, then display the sum.\n\n#include<iostream.h>\nclass Point\n{\n int x, y;\npublic:\n Point(int xx = 10, int yy = 20) { x = xx; y = yy; }\n Point operator+(Point objPoint)\n {\n Point objTmp;\n objTmp.x = objPoint.x + this->x;\n objTmp.y = objPoint.y + this->y;\n return objTmp;\n }\n void Display() { cout << x << " " << y; }\n};\nint main()\n{\n Point objP1; // 10,20\n Point objP2(1, 2); // 1,2\n Point objP3 = objP1 + objP2;\n objP3.Display();\n return 0;\n}

Difficulty: Easy

Correct Answer: 11 22

Explanation:


Introduction / Context:
This problem tests basic operator overloading and default constructor usage. The overloaded operator+ forms a new Point as the coordinate-wise sum of the two operands.


Given Data / Assumptions:

  • objP1 is initialized to (10,20) via defaults.
  • objP2 is initialized to (1,2).
  • objP3 = objP1 + objP2 invokes the overloaded operator.


Concept / Approach:
Inside operator+, objTmp.x = objPoint.x + this->x and similarly for y. With this->x=10 and objPoint.x=1, the result is (11,22).


Step-by-Step Solution:
Compute x: 1 + 10 = 11.Compute y: 2 + 20 = 22.Return a temporary with (11,22) and print it.


Verification / Alternative check:
Add debug prints inside operator+ to display operands and the result.


Why Other Options Are Wrong:
1 2 and 10 20 are the inputs, not the sum; garbage or compile errors do not apply.


Common Pitfalls:
Mixing operand order does not matter here because addition is commutative; the code still sums correctly.


Final Answer:
11 22

More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion