Search code examples
c++virtual-functionsvtabledynamictypevptr

Is virtual table necessary for C++?


I have a doubt about C++ virtual table recently.

Why does C++ use virtual table?

=>Because C++ compiler does not know the actual function address

--->Why?

=>Because C++ compiler does not know the exact type(Cat? Dog? Animal?) of the object the pointer "panimal" points to

---Why? Is that any way compiler can figure out the object type?

=>Yes, I think the compiler can make it via tracking object type.

Let's consider the sources where an object pointer gets its value. 2 sources indeed.

  1. another pointer
  2. address of class instance Where does "another pointer" get its value? Eventually, there's a pointer that gets its value from "class instance".

So, via tracking the assignment thread backwards to the original source object

  => the compiler is able to figure out the exact type of a pointer.

  =>the compiler knows the address of the exact function being called

  =>no virtual table is needed.

Object type tracking saves both virtual table memery and virtual table pointer of each class instances.

Where does object type tracking not work?

Library Linking.

If a library function returns a base-class pointer, there's no way for the compiler to track back to the original source object. The compiler can probably adapt to library code and none-library code. For library classes that are exported out, use virtual table. For other classes, just track theire object type to save memory.

I am not sure whether there's some error in above statements, please kindly point it out if any. Thanks in advance~


Solution

  • In some cases, yes, the compiler can figure out the type a pointer points to at compile time. It is quite easy to construct a case where it cannot though.

    int x;
    cin >> x;
    Animal* p;
    if (x == 10)
        p = new Cat();
    else
        p = new Dog();
    

    If the compiler can, in all cases, prove the type of an object, it is free to eliminate virtual tables from its generated code, as per the as-if rule.