zoukankan      html  css  js  c++  java
  • C++: virtual inheritance and Cross Delegation

    Link1: Give an example

    Note: I think the Storable::Write method should also be pure virtual.

    http://www.cprogramming.com/tutorial/virtual_inheritance.html

    Link2: explained from the vritual table point of view, Key point: as virual inheritance, complier will merge the virtual table of sisters for their multi-inheritanted son.

    http://stackoverflow.com/questions/4487914/which-function-to-call-delegate-to-a-sister-class

    Quote:

     

    What is happening behind the scene.

    The simple explanation is that, because inheritance from Base is virtual in both Der1 and Der2, there is a single instance of the object in the most derived object Join. At compile time, and assuming (which is the common case) virtual tables as dispatch mechanism, when compiling Der1::foo it will redirect the call to bar() through the vtable.

    Now the question is how the compiler generates vtables for each of the objects, the vtable for Base will contain two null pointers, the vtable for Der1 will contain Der1::foo and a null pointer and the vtable for Der2 will contain a null pointer and Der2::bar [*]

    Now, because of virtual inheritance in the previous level, when the compiler processes Join it will create a single Base object, and thus a single vtable for the Base subojbect of Join. It effectively merges the vtables of Der1 and Der2 and produces a vtable that contains pointers to Der1::foo and Der2::bar.

    So the code in Der1::foo will dispatch through Join's vtable to the final overrider, which in this case is in a different branch of the virtual inheritance hierarchy.

    If you add a Der3 class, and that class defines either of the virtual functions, the compiler will not be able to cleanly merge the three vtables and will complain, with some error relating to the ambiguity of the multiply defined method (none of the overriders can be considered to be the final overrider). If you add the same method to Join, then the ambiguity will no longer be a problem, as the final overrider will be the member function defined in Join, so the compiler is able to generate the virtual table.

    [*] Most compilers will not write null pointers here, but rather a pointer to a generic function that will print an error message and terminate the application, allowing for better diagnostics than a plain segmentation fault.

  • 相关阅读:
    二十一.组合模式
    二十四.桥接模式
    二十六.职责链模式
    二十五.命令模式
    将小写转化成大写
    备份JOB SCHEDULE ENTRY的简单方法
    如何确定哪一个作业锁定QDLS下的一个目标
    WRKACTJOB命令一些有用功能介绍
    如何使用CA/400批处理的方式传输数据
    用前缀给字段命名
  • 原文地址:https://www.cnblogs.com/hellohelloworld/p/5631160.html
Copyright © 2011-2022 走看看