In C++ (passing references to a constructor), determine the program's output. The constructor takes two int& parameters and prints the stored values.
#include
class CuriousTab
{
int x, y;
public:
CuriousTab(int &xx, int &yy)
{
x = xx;
y = yy;
Display();
}
void Display()
{
cout << x << " " << y;
}
};
int main()
{
int x1 = 10; int &p = x1;
int y1 = 20; int &q = y1;
CuriousTab objCuriousTab(p, q);
return 0;
}
-
AIt will result in a compile time error.
-
BThe program will print the output 10 20.
-
CThe program will print two garbage values.
-
DThe program will print the address of variable x1 and y1.
Answer
Correct Answer: The program will print the output 10 20.
Explanation
Introduction / Context: This checks basic reference passing into a constructor and immediate printing via a member function. The references are bound to existing lvalues and then copied into data members.
Given Data / Assumptions:
- p binds to x1 (10), q binds to y1 (20).
- Constructor copies values into x and y, then Display() prints them.
Concept / Approach: Since the parameters are references, they safely bind to the provided lvalues. Inside the constructor, assignments copy those values into the object. Display then prints the pair.
Step-by-Step Solution:
x receives 10, y receives 20. Display prints "10 20".Verification / Alternative check: If p or q were changed after construction, the object would not reflect changes because x and y store copies, not references.
Why Other Options Are Wrong: No compile error or garbage printing occurs; addresses are not printed since the stream inserts ints.
Common Pitfalls: Confusing reference parameters with reference data members; here only parameters are references.
Final Answer: The program will print the output 10 20.