I do not understand why compiling the second version of the fragment. AFAIK he should not, because of ยง10.3 / 2

This code does not compile due to ยง10.3 / 2, i.e. A virtual function A::fhas more than one final override in D.

#include <iostream>

class A { public: virtual void f(){ std::cout << "A::f" << '\n'; } };
class B : public virtual A { public: void f(){ std::cout << "B::f" << '\n'; } };
class C : public virtual A { public: void f(){ std::cout << "C::f" << '\n'; } };
class D : public B, public C { };

int main()
{
    D d;
    d.f();
}

But contrary to my expectations, this code compiles. Given that this sentence is contained in ยง10.3 / 2 For convenience we say that any virtual function overrides itself, it seems to me that we have the same problem here, that is, a virtual function A::fhas more than one finite override in D, that is, A::fand C::f. Actually the call d.f()is causing C::f. Why is this?

#include <iostream>

class A { public: virtual void f(){ std::cout << "A::f" << '\n'; } };
class B : public virtual A {};
class C : public virtual A { public: void f(){ std::cout << "C::f" << '\n'; } };
class D : public B, public C { };

int main()
{
    D d;
    d.f();
}
+4
source share
1

, , :

- C::vf S , (1.8), S ( ), , vf. , overrider .

.

. D A - A1 A2. A::f A::f A1 B. C::f C (A2 ). D , , A::f D.

A, B, C. A::f B, , B ( , D), -, A::f ( , C::f).

, , , A::f D. C::f A::f C D; A B .

, C::f:

// Setup the same as in the OP example:
D d;
B* pB = &d;
pB->f();  // calls C::f, not A::f
0

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


All Articles