C++ nested struct as a global member: if a function that initializes members is never called, what does Display() print?\n\n#include<iostream.h>\nclass India\n{\npublic:\n struct CuriousTab\n {\n int x;\n float y;\n void Function()\n {\n y = x = (x = 4 * 4);\n y = --y * y;\n }\n void Display()\n {\n cout << y << endl;\n }\n } B;\n} I;\nint main()\n{\n I.B.Display();\n return 0;\n}

Difficulty: Medium

Correct Answer: 0

Explanation:


Introduction / Context:
This item tests default initialization rules for objects with static storage duration and the effect of not invoking an initializing member function. The code defines a global object I of type India which, in turn, contains a subobject B of a nested struct.


Given Data / Assumptions:

  • I is defined at namespace scope (global).
  • B is a non-static data member of I and therefore part of a global object.
  • Function() is never called in main.
  • Display() prints the value of y.


Concept / Approach:
Objects with static storage duration (globals) are zero-initialized before any dynamic initialization occurs. Since Function() is never invoked, x and y retain their zero-initialized values. Therefore, Display() prints 0.


Step-by-Step Solution:
Because I is global, I.B.x and I.B.y start as 0.No call to I.B.Function() occurs; thus values are unchanged.Printing y outputs 0 followed by a newline.


Verification / Alternative check:
Add a call to I.B.Function() before Display() to see a non-zero result.


Why Other Options Are Wrong:
Options B/C/D assume either one or negative/indeterminate values; zero-initialization for globals guarantees 0 here.


Common Pitfalls:
Assuming uninitialized garbage for globals; in C++, globals are zero-initialized, unlike certain local automatic variables.


Final Answer:
0

More Questions from Objects and Classes

Discussion & Comments

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