C++ operator overloading for a 2D point: compute the result of Point operator+(Point) with default and explicit constructors, then display the sum.
#include
class Point
{
int x, y;
public:
Point(int xx = 10, int yy = 20) { x = xx; y = yy; }
Point operator+(Point objPoint)
{
Point objTmp;
objTmp.x = objPoint.x + this->x;
objTmp.y = objPoint.y + this->y;
return objTmp;
}
void Display() { cout << x << " " << y; }
};
int main()
{
Point objP1; // 10,20
Point objP2(1, 2); // 1,2
Point objP3 = objP1 + objP2;
objP3.Display();
return 0;
}
-
A1 2
-
B10 20
-
C11 22
-
DGarbage Garbage
-
EThe program will report compile time error.
Answer
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:
objP1is initialized to(10,20)via defaults.objP2is initialized to(1,2).objP3 = objP1 + objP2invokes 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