The table of virtual functions [provided that the C ++ compiler implements dynamic distribution] is used for all objects of the class. However, each object must know which virtual function table is related to this object. This is what the "virtual function table pointer" points to.
The main idea is that the static type of the link or the pointer to the object tells the compiler what the part of the virtual function table looks like. When he needs to do a virtual dispatch, he simply follows this pointer and decides which function to call. Suppose you have a base class B and derived classes D1 and D2 as follows:
#include <iostream> struct B { virtual ~B() {} virtual void f() = 0; }; struct D1: public B { void f() override { std::cout << "D1::f()\n"; } }; struct D2: public B { void f() override { std::cout << "D2::f()\n"; } };
The virtual function table for D1 and D2 will contain a suitable pointer to D1::f() and D2::f() respectively. When the compiler sees a call through a pointer or a reference to B before f() , it needs to decide at runtime which function to call:
void g(B* base) { base->f(); }
To resolve the call, he looks where the pointer to the virtual function is and calls the function n in the corresponding slot (more or less, the contents of the virtual function table tend to be loud, which may also require correction of the pointer).
source share