Why do we need virtual table?

前端 未结 5 1995
执念已碎
执念已碎 2020-12-03 11:42

I was looking for some information about virtual table, but can\'t find anything that is easy to understand.
Can somebody give me good examples(not from Wiki, please) wi

5条回答
  •  一向
    一向 (楼主)
    2020-12-03 12:09

    Suppose Player and Monster inherit from an abstract base class Actor that defines a virtual name() operation. Further suppose that you have a function that asks an actor for his name:

    void print_information(const Actor& actor)
    {
        std::cout << "the actor is called " << actor.name() << std::endl;
    }
    

    It is impossible to deduce at compile time whether the actor will actually be a player or a monster. Since they have different name() methods, the decision which method to call must be deferred until runtime. The compiler adds additional information to each actor object that allows this decision to be made at runtime.

    In every compiler I know, this additional information is a pointer (often called vptr) to a table of function pointers (often called vtbl) that are specific to the concrete class. That is, all player objects share the same virtual table which contains pointers to all player methods (same goes for the monsters). At runtime, the correct method is found by choosing the method from the vtbl pointed to by the vptr of the object on which the method should be invoked.

提交回复
热议问题