CPA-21-02 practice question 31 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; class First { public: void Print(){ cout

Full set: 257 questions
Answer options
A: It prints: from First
B: It prints: from Firstfrom First
C: It prints: from Secondfrom Second Correct answer
D: It prints: from Second
Correct Answer:
C. It prints: from Secondfrom Second
Explanation

The main function creates an array named t containing two objects of the Second class (Second t[2];). The for loop iterates twice (for i=0 and i=1). During each iteration, it calls the Print() member function on the respective Second object in the array (t[i].Print()). The Second::Print() function outputs the string "from Second" using cout. Because there are no newline characters (\n or endl) in the output stream, the strings are printed consecutively, resulting in the output "from Secondfrom Second".

Why Incorrect

A. The array is instantiated with objects of the Second class, not the First class, so First::Print() is never called.
B. The program calls the Print method of the Second class, so it will not output the string associated with the First class.
D. The loop executes two times, meaning the string is printed twice consecutively, not just once.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 12.2 [class.mem], Paragraph 1 on member function invocation.

2. ISO/IEC 14882:2017 (C++17 Standard), Section 9.2.3.4 [dcl.array], Paragraph 1 on array declarations and element access.

Scroll to Top