Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

In the 3rd code example here the comment says that C::f overrides A::f. Why is this? My intuition says that it should override 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
}
like image 278
LearningMath Avatar asked Dec 13 '22 22:12

LearningMath


1 Answers

The text of the C++14 standard is (class.virtual/2):

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. For convenience we say that any virtual function overrides itself.

So C::f overrides all of A::f, B::f and C::f.

like image 108
M.M Avatar answered Dec 27 '22 21:12

M.M