Search code examples
c++vtable

Can we have one vtable shared my multiple classes


Is it possible in C++ to have one vtable shared by multiple classes? As per my understanding if a class is having a virtual function then it will generate a vtable.So every class should have its own vtable.


Solution

  • Polymorphism could be implemented several ways. And vtables could also be implemented several ways. But usually in following case

    class A {
        virtual foo(){}
    }
    
    class B : public A {
        virtual foo(){}
    }
    
    class C : public B {
        void fooNonVirtual(){};
    }
    

    classes B and C should have the same vtable.

    Example:

    A *a = new A;
    B *b = new B;
    C *c = new C;
    a->foo(); // A::foo is called
    ((A*)b)->foo(); // B::foo is called
    ((A*)c)->foo(); // B::foo is called
    

    foo for a and b calls different methods because A and B has different vtables. For b and c the same method is called. So compiler could make some optimization and create only one vtable for B and C classes.

    fooNonVirtual is not virtual and do not require vtables at all.