Deal of The Day! Hurry Up, Grab the Special Discount - Save 25% - Ends In 00:00:00 Coupon code: SAVE25
Welcome to Pass4Success

- Free Preparation Discussions

C++ Institute CPA-21-02 Exam - Topic 1 Question 52 Discussion

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
D) Compilation error
A) It prints: 210
B) It prints: 110
C) It prints: 010

C++ Institute CPA-21-02 Exam - Topic 1 Question 52 Discussion

Actual exam question for C++ Institute's CPA-21-02 exam
Question #: 52
Topic #: 1
[All CPA-21-02 Questions]

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 << c1.x;

return 0;

}

Show Suggested Answer Hide Answer
Suggested Answer: D

Contribute your Thoughts:

0/2000 characters
Alishia
25 days ago
No way, it should be a compilation error!
upvoted 0 times
...
Lenora
30 days ago
It prints: 010
upvoted 0 times
...
Rupert
1 month ago
I’m leaning towards a compilation error because of the private inheritance from B. I don’t think main can access x in class C.
upvoted 0 times
...
Lou
2 months ago
I practiced a similar question where inheritance affected variable access. I think this one might print 0 or 1, but I can't recall exactly how private inheritance works here.
upvoted 0 times
...
Adelaide
2 months ago
I remember something about private inheritance. I feel like that might prevent access to x in class C, which could lead to a compilation error.
upvoted 0 times
...
Chaya
2 months ago
I think the code will compile, but I'm not sure what value will be printed. It seems like it should be 2 since C sets x to 2.
upvoted 0 times
...

Save Cancel