Why does this code say that C :: f overrides A :: f, but not B :: f?

In the 3rd code example, the comment here says that C :: f overrides A :: f. Why is this? My intuition says that it should redefine B :: f.

struct A { virtual void f(); };     // A::f is virtual
struct B : A { void f(); };         // B::f overrides A::f in B
struct C : virtual B { void f(); }; // C::f overrides A::f in C
struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D
struct E : C, D  {       // E does not introduce an overrider, C::f is final in E
    using A::f; // not a function declaration, just makes A::f visible to lookup
};
int main() {
   E e;
   e.f();    // virtual call calls C::f, the final overrider in e
   e.E::f(); // non-virtual call calls A::f, which is visible in E
}
+4
source share
2 answers

Virtual base classes apply only to data members, not to methods.

It doesn't matter if it overrides C::f A::for B::f- it's the same thing.

This comment can be changed to C::foverride B::f, and it still means the same thing.

Consider the following hierarchy (without virtual base classes)

class A { virtual void foo(); }
class B : public A { void foo(); }
class C : public B { void foo(); }

B::foo A::foo. C::foo B::foo. , C::foo A::foo.

, , . , .

+6

++ 14: (class.virtual/2):

- vf ​​ Base Derived, Base, - vf , --, cv-qualification ref-qualifier ( ), Base::vf, Derived::vf ( , ), Base::vf. , .

, C::f A::f, B::f C::f.

+6

Source: https://habr.com/ru/post/1680674/


All Articles