understanding vptr in multiple inheritance?

后端 未结 5 2039
暗喜
暗喜 2021-01-30 11:59

I am trying to make sense of the statement in book effective c++. Following is the inheritance diagram for multiple inheritance.

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 12:26

    I could not see any reason why there is requirement of separate memory in each class for vptr

    At runtime, when you invoke a (virtual) method via a pointer, the CPU has no knowledge about the actual object on which the method is dispatched. If you have B* b = ...; b->some_method(); then the variable b can potentially point at an object created via new B() or via new D() or even new E() where E is some other class that inherits from (either) B or D. Each of these classes can supply its own implementation (override) for some_method(). Thus, the call b->some_method() should dispatch the implementation from either B, D or E depending on the object on which b is pointing.

    The vptr of an object allows the CPU to find the address of the implementation of some_method that is in effect for that object. Each class defines it own vtbl (containing addresses of all virtual methods) and each object of the class starts with a vptr that points at that vtbl.

提交回复
热议问题