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 questionsThe 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).
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).
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).
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 1What happens when you attempt to compile and run the following code? #include using names…
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 6What happens when you attempt to compile and run the following code? #include using names…
