Search code examples
c++vtable

Where is pure virtual function located in C++?


Which virtual table will be pure virtual function located? In the base class or derived class?

For example, what does the virtual table look like in each class?

class Base {

  virtual void f() =0;
  virtual void g();
}


class Derived: public Base{

  virtual void f();
  virtual void g();

}

Solution

  • g++ -fdump-class-hierarchy layout.cpp produces a file layout.cpp.class. The content of layout.cpp.class will show the following:

    Vtable for Base
    Base::_ZTV4Base: 4u entries
    0     (int (*)(...))0
    8     (int (*)(...))(& _ZTI4Base)
    16    __cxa_pure_virtual
    24    Base::g
    
    Class Base
       size=8 align=8
       base size=8 base align=8
    Base (0x7ff893479af0) 0 nearly-empty
        vptr=((& Base::_ZTV4Base) + 16u)
    
    Vtable for Derived
    Derived::_ZTV7Derived: 4u entries
    0     (int (*)(...))0
    8     (int (*)(...))(& _ZTI7Derived)
    16    Derived::f
    24    Derived::g
    
    Class Derived
       size=8 align=8
       base size=8 base align=8
    Derived (0x7ff893479d90) 0 nearly-empty
        vptr=((& Derived::_ZTV7Derived) + 16u)
      Base (0x7ff893479e00) 0 nearly-empty
          primary-for Derived (0x7ff893479d90)
    

    Removing the 'pureness' of f changes the fifth line to:

    16    Base::f