C++ nested struct as a global member: if a function that initializes members is never called, what does Display() print?
#include
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;
}
-
A0
-
B1
-
C-1
-
DGarbage value
-
EIt depends on compiler optimization.
Answer
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:
Iis defined at namespace scope (global).Bis a non-static data member ofIand therefore part of a global object.Function()is never called inmain.Display()prints the value ofy.
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