virtual method table for multiple-inheritance

后端 未结 2 945
花落未央
花落未央 2021-01-12 09:39

I\'m reading this article \"Virtual method table\"

Example in the above article:

class B1 {
public:
  void f0() {}
  virtual void f1() {}
  int int_i         


        
2条回答
  •  醉酒成梦
    2021-01-12 09:41

    We cannot pass the D pointer to a virtual function overriding B2::f2(), because all overrides of the same virtual function must accept identical memory layout.

    Since B2::f2() function expects B2's memory layout of the object being passed to it as its this pointer, i.e.

    b2:
      +0: pointer to virtual method table of B2
      +4: value of int_in_b2
    

    the overriding function D::f2() must expect the same layout as well. Otherwise, the functions would no longer be interchangeable.

    To see why interchangeability matters consider this scenario:

    class B2 {
    public:
      void test() { f2(); }
      virtual void f2() {}
      int int_in_b2;
    };
    ...
    B2 b2;
    b2.test(); // Scenario 1
    D d;
    d.test(); // Scenario 2
    

    B2::test() needs to make a call of f2() in both scenarios. It has no additional information to tell it how this pointer has to be adjusted when making these calls*. That is why the compiler passes the fixed-up pointer, so test()'s call of f2 would work both with D::f2() and B2::f2().

    * Other implementations may very well pass this information; however, multiple inheritance implementation discussed in the article does not do it.

提交回复
热议问题