C++ default argument as null pointer to a 2D array parameter and uninitialized storage: what will this program display? #include<iostream.h> class CuriousTabArray { int array[3][3]; public: CuriousTabArray(int arr[3][3] = NULL) { if (arr != NULL) for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) array[i][j] = i + j; } void Display(void) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) cout << array[i][j] << " "; } }; int main() { CuriousTabArray objBA; // uses default argument NULL objBA.Display(); return 0; }
-
AThe program will report error on compilation.
-
BThe program will display 9 garbage values.
-
CThe program will display NULL 9 times.
-
DThe program will display 0 1 2 1 2 3 2 3 4.
-
EThe program will print nothing.
Answer
Correct Answer: The program will display 9 garbage values.
Explanation
Introduction / Context:
This item explores default arguments, pointer conversion of array parameters, and uninitialized memory. The constructor accepts a parameter written as int arr[3][3], which actually decays to a pointer-to-array type; a default of NULL (zero pointer constant) is supplied. If no argument is passed, the body skips initialization, leaving the member array with indeterminate values.
Given Data / Assumptions:
- Default argument
NULLis used whenobjBAis created. - The
if (arr != NULL)guard prevents any assignments. array[3][3]is a non-static data member with no in-class initializer.
Concept / Approach: In C++, built-in and POD members are not implicitly zero-initialized for automatic objects unless you explicitly do so. Because the constructor does nothing when arr == NULL, each element of array remains uninitialized (indeterminate). Streaming such values yields unspecified “garbage”.
Step-by-Step Solution: 1) Construct with default: arr == NULL. 2) Branch skips the initialization loop. 3) Display() iterates 9 elements and prints whatever bit patterns were in memory. 4) Therefore, nine garbage values appear separated by spaces.
Verification / Alternative check: Pass a real array to the constructor to execute the loop and you would see the predictable sequence “0 1 2 1 2 3 2 3 4”.
Why Other Options Are Wrong: Compilation is permitted; “NULL” is not printed literally; the specific numeric pattern (0..4) only appears if initialization runs.
Common Pitfalls: Assuming members are zeroed automatically; misunderstanding default arguments with array parameters.
Final Answer: The program will display 9 garbage values.