CPA-21-02 practice question 27 of 35

What happens when you attempt to compile and run the following code? #include #include using namespace std; class A { public: int x; A() { x=0;} A(int x) { this?>x=x;} }; class B : private A { public: using A::x; B() { x=1;} B(int x) {this?>x = x;} }; int main () { B c1; B c2(?5); cout

Full set: 257 questions
Answer options
A: It prints: 5
B: It prints: 1?5 Correct answer
C: It prints: 05
D: It prints: 0
Correct Answer:
B. It prints: 1?5
Explanation

The code uses private inheritance (class B : private A), making A's public members private in B. However, the using A::x; declaration restores x to public access in B. The default constructor B() sets x to 1. The parameterized constructor B(int x) sets x to the passed argument. (Note: The ? in this?>x and ?5 are typographical OCR artifacts representing the minus sign - and -> operator). B c1; calls the default constructor, setting c1.x to 1. B c2(-5); calls the parameterized constructor, setting c2.x to -5. Printing both results in "1-5" (represented as "1?5" in the options due to the same artifact).

Why Incorrect

A: Incorrect because it only accounts for the second object's output, completely missing the output from c1. C: Incorrect because B's constructors execute after A's, overriding the initialization done by A, so c1.x is 1, not 0. D: Incorrect because it does not reflect the values assigned by B's constructors (1 and -5).

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 10.3.3 [namespace.udecl], Paragraph 1 (The using declaration for class members).

2. ISO/IEC 14882:2017 (C++17 Standard), Section 14.2 [class.access.base], Paragraph 1-2 (Access specifiers and private inheritance).

3. Stroustrup, B. (2013). The C++ Programming Language (4th ed.). Addison-Wesley. Chapter 20.5 (Access Control).

Scroll to Top