C++ Quiz17 of 173
Difficulty:
⬅️ Prev: 17Quiz ID: 18Next: 24 ➡️

According to the C++23 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);
}
Hint

What is the type of the expression a? What is the dynamic type of a? Which of these is used for access checking, and which is used to select which f() to call?

Reveal answer

B

Explanation

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&.

⬅️ Prev: 17Quiz ID: 18Next: 24 ➡️