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

Question #18 Difficulty: 1

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

    #include <iostream>

class A {
public:
  virtual void f() { std::cout << "A"; }
};

class B : public A {
private:
  void f() { std::cout << "B"; }
};

void g(A &a) { a.f(); }

int main() {
  B b;
  g(b);
}

Correct!

The "trick" here is that B::f() is called even though it is private.

As §[class.access.virt]¶2 in the standard puts it: "Access is checked at the call point using the type of the expression used to denote the object for which the member function is called". The call point here being a.f(), and the type of the expression is A&.

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.