We're porting the questions to C++23! Can you help?

You've answered 1 of 163 questions correctly. (Clear)

Question #312 Difficulty: 1

According to the C++23 standard, what is the output of this program?

    #include <iostream>

class A {};

class B {
public:
    int x = 0;
};

class C : public A, B {};

struct D : private A, B {};


int main()
{
    C c;
    c.x = 3;

    D d;
    d.x = 3;

    std::cout << c.x << d.x;
}

Correct!

x is a public member of B, which is a base class of C and D. Which accessibility does x have in C and D?

§[class.access.base]¶1:

If a class is declared to be a base class (§[class.derived]) for another class using the public access specifier, the public members of the base class are accessible as public members of the derived class (...). If a class is declared to be a base class for another class using the private access specifier, the public (...) members of the base class are accessible as private members of the derived class.

So any public members from A (there are none in this example) would be public in C, and private in D. But what about B, where x is defined? Are C and D deriving publicly or privately from B when there is no access-specifier?

§[class.access.base]¶2:

In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.

So since we don't provide an access-specifier for B, class C derives privately from B, making x private. And struct D derives publicly from B, making x public.

This means the line c.x = 3 has a compilation error since x is private.

You can explore this question further on C++ Insights or Compiler Explorer!

Next question

Mode : Training

You are currently in training mode, answering random questions. Why not Start a new quiz? Then you can boast about your score, and invite your friends.

Contribute

Create your own!

Android app

Get Sergey Vasilchenko's CppQuiz Android app.

C++ Brain Teasers

Get the book, support the site! C++ Brain Teasers cover