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.\n\n#include<iostream.h>\nclass Tab\n{\n int x, y;\npublic:\n void show(void);\n void main(void);\n};\nvoid Tab::show(void)\n{\n Tab b;\n b.x = 2;\n b.y = 4;\n cout << x << " " << y;\n}\nvoid Tab::main(void)\n{\n Tab b;\n b.x = 6;\n b.y = 8;\n b.show();\n}\nint main(int argc, char *argv[])\n{\n Tab run;\n run.main();\n return 0;\n}\n\nWhat exactly is printed to stdout?

Difficulty: Medium

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

More Questions from Functions

Discussion & Comments

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