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

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