Confusion over how base class finds the correct method in dynamic dispatch for overridden methods with vtable implementations

72 views Asked by At

This question can be summed up as: where is the missing arrow?

I was reading Chapter 4 of A Tour of C++ 2nd Edition by Bjarne Stroustrup and couldn't understand how a base pointer to a derived object was able to find the correct method to call when it came to virtual functions. Here's the example provided for 2 derived classes from Container.

class Container {
public:
    virtual double& operator[](int) = 0; // pure virtual function
    virtual int size() const = 0; // const member function (§4.2.1)
    virtual ~Container() {} // destr uctor (§4.2.2)
};

vtbl in Stroustrup book

The function that will be used for Container-like object is:

void use(Container& c)
{
const int sz = c.size();
for (int i=0; i!=sz; ++i)
    std::cout << c[i] << '\n';
}

I understand that vtables or virtual function tables are an implementation detail and are not part of the C++ standard. It is the implementation detail that I would like to understand.

I didn't understand how a pointer to a base class as a function parameter would allow a derived class instance argument so I went on to search other explanations. This tutorial shows another drawing where the vtable pointer is mentioned but doesn't quite go into detail as to how a Base* figures out a Derived object.

The confusion I have is that, to me, t would seem to make sense for Base* to have pointers to all the other methods of the derived classes so that when the pointer is called, it could do a "cast" (in quotes because I don't think a cast is efficient) and then figure out the correct method to call. However, this seems convoluted and a "cast" would be expensive. In the example below, it seems like Base* has some information about what it is pointing to but there is no arrow to the derived class vtable. How does it know that it is pointing to a derived object as there are no arrows in the diagram below? Is there an arrow missing in the illustration?

drawing of vtable

This tutorial has a similar representation but I can't seem to get where the "missing" arrow is. From my understanding, there is only one of Class B and Class C blueprints and that each new object uses this to create its own copy so we would have the blueprints in memory and the actual instances in the heap/free store when we use new. extra diagram

To make sure I don't get downvoted for not doing research. Here are some questions I have looked at that mentioned dynamic dispatch: question 1, question 2. They are all for Java not C++.

0

There are 0 answers