In C++ (old-style headers shown), analyze operator overloading, reference binding, and assignment through a reference. What will the following program print?
#include
class CuriousTab
{
int x, y;
public:
CuriousTab(int xx = 0, int yy = 0)
{
x = xx;
y = yy;
}
void Display()
{
cout << x << " " << y;
}
CuriousTab operator +(CuriousTab z)
{
CuriousTab objTemp;
objTemp.x = x + z.x;
objTemp.y = y + z.y;
return objTemp;
}
};
int main()
{
CuriousTab objCuriousTab1(90, 80);
CuriousTab objCuriousTab2(10, 20);
CuriousTab objSum;
CuriousTab &objRef = objSum;
objRef = objCuriousTab1 + objCuriousTab2;
objRef.Display();
return 0;
}
-
AIt will result in a runtime error.
-
BIt will result in a compile time error.
-
CThe program will print the output 9 4.
-
DThe program will print the output 100 100.
Answer
Correct Answer: The program will print the output 100 100.
Explanation
Introduction / Context: This problem checks C++ operator overloading for user-defined types, reference binding to an lvalue object, and calling a member function through a reference after assignment. The code uses an overloaded operator+ that returns a new temporary object whose x and y are element-wise sums.
Given Data / Assumptions:
- CuriousTab stores two ints x and y.
- operator+ forms a temporary with (x + z.x, y + z.y).
- objRef is a reference bound to objSum, so assignments through objRef modify objSum.
- Initial values: objCuriousTab1 = (90, 80), objCuriousTab2 = (10, 20).
Concept / Approach: Compute the sum via the overloaded operator, assign the resulting temporary to objRef (alias of objSum), and then display the stored pair. No dynamic memory or undefined behavior is present; the code is well-formed with old iostream headers.
Step-by-Step Solution:
Sum = (90 + 10, 80 + 20) = (100, 100) objRef = Sum; // assigns to objSum via reference objRef.Display() prints "100 100"Verification / Alternative check: If Display were called on objSum directly, it would print the same, proving objRef truly aliases objSum.
Why Other Options Are Wrong:
- Runtime/compile errors: None are present here.
- "9 4": Not related to the arithmetic performed.
Common Pitfalls: Confusing reference binding with copying; here objRef and objSum are the same object. Also, operator+ returns a temporary which is then assigned, not a reference to a local.
Final Answer: The program will print the output 100 100.