CPA-21-02 practice question 11 of 35

What happens when you attempt to compile and run the following code? #include #include using namespace std; class A { int x; protected: int y; public: int z; A() { x=1; y=2; z=3; } }; class B : public A { string z; public: void set() { y = 4; z = "John"; } void Print() { cout

Full set: 257 questions
Answer options
A: It prints: 4John Correct answer
B: It prints: 2John
C: It prints: 23
D: It prints: 43
Correct Answer:
A. It prints: 4John
Explanation

Class B publicly inherits from class A. The member y is declared as protected in A, making it directly accessible to the derived class B. Class B also declares a member string z, which hides the inherited public int z from A due to name hiding rules. When b.set() is called, it updates the inherited y to 4 and the local string z to "John". The Print() method outputs y followed by z without any spaces, resulting in the output "4John".

Why Incorrect

B. Incorrect because the set() method explicitly updates the value of y from its initial value of 2 to 4 before printing.
C. Incorrect because y is updated to 4, and the name z in class B refers to the string "John", hiding the integer z (3) from class A.
D. Incorrect because the local string z in class B hides the inherited int z from class A. It prints "John", not 3.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 14.2 [class.access.base], Paragraph 1 (Access control of base classes).

2. ISO/IEC 14882:2017 (C++17 Standard), Section 6.3.10 [basic.scope.hiding], Paragraph 1-3 (Name hiding).

3. MIT OpenCourseWare, 6.096 Introduction to C++, Lecture 8: Inheritance and Polymorphism.

Scroll to Top