c++polymorphismvirtual-functionsvirtual-table

Why the need of virtual tables on calling virtual functions at runtime?


I was following this tutorial, trying to understand virtual table and the whole process behind pointer and virtual functions in C++.

Not sure, when I have code like this:

D1 d1;
Base *dPtr = &d1;
dPtr->function1();

Why do I need all of this virtual table management? Why compiler simply don't assign the memory address of d1 (or base, if there aren't any) overridden virtual function?

I mean: it could elaborate there at compile time if it needs the D1 functon1() address or Base functon1() address. It know at that time. Why lose time and resources later at runtime looking on virtual tables?

I miss this point. Fancy example?


Solution

  • This is my function:

    void foo(Base *pBase) {
      pBase->function1();
    }
    

    I compile it in isolation and give you an object file with a header. Months before you even dream up of D1. How would the compiler "use the address of D1's function1 directly" here?

    It can't. That's why some form of indirection is required.

    Beyond that, a virtual function table isn't required in the sense that every C++ implementation would use one. It's just the most popular implementation technique employed by compilers today.