What function to call? (delegate in sister class)

I just read about it in the C ++ FAQ Lite

[25.10] What does it mean to “delegate to the sister class” through virtual inheritance?

 class Base {
 public:
   virtual void foo() = 0;
   virtual void bar() = 0;
 };

 class Der1 : public virtual Base {
 public:
   virtual void foo();
 };

 void Der1::foo()
 { bar(); }

 class Der2 : public virtual Base {
 public:
   virtual void bar();
 };

 class Join : public Der1, public Der2 {
 public:
   ...
 };

 int main()
 {
   Join* p1 = new Join();
   Der1* p2 = p1;
   Base* p3 = p1;

   p1->foo();
   p2->foo();
   p3->foo();
 } 

"Believe it or not, when Der1 :: foo () calls this-> bar (), it ends the call to Der2 :: bar (). Yes, that's right: a class that Der1 knows nothing will provide an override of the virtual function called Der1 :: foo (). This "cross-delegation" can be a powerful way to customize the behavior of polymorphic classes. "

My question is:

  • What happens behind the scenes.

  • If I add Der3 (virtual inherited from Base), what happens? (I do not have a compiler here, I can not check it right now.)

+3
source share
5

.

, Base Der1, Der2, Join . ( ) , Der1::foo bar() vtable.

, vtables , vtable Base , vtable Der1 Der1::foo , vtable Der2 Der2::bar [*]

, - , Join, Base , , vtable Base subojbect Join. vtables Der1 Der2 vtable, Der1::foo Der2::bar.

, Der1::foo Join vtable , .

Der3, , vtables , , ( ). Join, , -, Join, .

[*] , , terminate , , .

+6

Der3, , , .

, ; . .

Der1 Der2 , Der1, bar() - Der2, foo() .

Join , .

, , dynamic_casting.

, , - , .

, , Join. , . .

+1

, . , , . , - , fix-this-bad-design-to-work-howhow, .

VS2010 - , . , -, .

Der3,

class Der3 : public virtual Base {
public:
    void bar() {}
};

class Join : public Der1, public Der2, public Der3 {}

- ambiguous inheritance of 'void Base::bar(void)'

0

( , ). . : ( ). , Der1 Der2, 4 32 8 64 . , , . , Join, Virtual Base ( ), , Der1 Der2 construtor). Join / , , Der1 Der2 . sizeof. , . Virtual Base Depth First way. ( , ). .

0
source

This is a pretty dumb example of imo and a great example of academics who look smart. If this situation ever appeared, it would be CONSTANT due to an error, especially forget to make Der1 :: foo () virtual.

Edit:

I am not reading class definitions correctly. This is precisely the problem with this type of construction. It takes a lot of thought to determine exactly what will happen in each of these cases, which is bad. Making your code readable is much better than being as smart as this.

-1
source

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


All Articles