CPA-21-02 practice question 20 of 35

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

Full set: 257 questions
Answer options
A: It prints: 210
B: It prints: 110
C: It prints: 010
D: Compilation error Correct answer
Correct Answer:
D. Compilation error
Explanation

The code results in a compilation error due to access control restrictions. Class C inherits from class B using the private access specifier (class C : private B). Consequently, all public members of B, including the inherited public member x from class A, become private members within the context of class C. When the main function attempts to access c1.x directly, the compiler rejects it because x is inaccessible from outside the class C.

Why Incorrect

A. Incorrect because the code will not compile, so it cannot produce any output.
B. Incorrect because the code will not compile, so it cannot produce any output.
C. Incorrect because the code will not compile, so it cannot produce any output.

References

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

- Bjarne Stroustrup, "The C++ Programming Language" (4th Edition), Chapter 20.5 (Access Control).

Scroll to Top