C++ (member access across objects) — predict the output printed by show() when it is invoked on an object whose fields were set just before the call.
#include
class Tab
{
int x, y;
public:
void show(void);
void main(void);
};
void Tab::show(void)
{
Tab b;
b.x = 2;
b.y = 4;
cout << x << " " << y;
}
void Tab::main(void)
{
Tab b;
b.x = 6;
b.y = 8;
b.show();
}
int main(int argc, char *argv[])
{
Tab run;
run.main();
return 0;
}
What exactly is printed to stdout?
-
A2 4
-
B6 8
-
CThe program will report error on Compilation.
-
DThe program will report error on Linking.
-
EThe program will report error on Run-time.
Answer
Correct Answer: 6 8
Explanation
Introduction / Context:This program tests understanding of member access across different instances of the same class in C++. The function show() constructs its own local object b but then prints the data members x and y of the current object (the one on which show() was called), not of the temporary b created inside show().
Given Data / Assumptions:
- Class Tab has two private ints: x and y.
- Tab::main creates a local object b, assigns b.x = 6 and b.y = 8, then calls b.show().
- Tab::show creates its own local Tab b, sets b.x = 2 and b.y = 4, but prints x and y of the current object.
- Assume an older environment where
is accepted (as used by many legacy MCQs).
Concept / Approach:Within a non-static member function, an unqualified member name (x, y) refers to this->x and this->y. Creating another instance inside the member function does not change which object this points to. As a member, show() can assign to private members of any Tab instance it has a reference to, but the cout line is explicitly referencing the current object’s fields.
Step-by-Step Solution:
Construct local b in Tab::main and set b.x = 6, b.y = 8.Call b.show(). Inside show(), a new local Tab b is created and set to (2, 4).The cout statement prints this->x and this->y from the caller object, which are 6 and 8.Therefore the output is the two numbers: 6 8.Verification / Alternative check:Rename the inner object to b2 and print b2.x, b2.y to see 2 4; but the given code does not do that, it prints the caller’s fields.
Why Other Options Are Wrong:
- 2 4: Would be printed only if the code printed the inner object’s members.
- Compilation/Link/Run-time errors: The code is valid in a legacy header setting and runs normally.
Common Pitfalls:Assuming that the most recently declared variable b is what gets printed; forgetting that x and y refer to this->x and this->y.
Final Answer:6 8