8

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();

}
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
skydoor
  • 25,218
  • 52
  • 147
  • 201
  • Related question: http://stackoverflow.com/questions/2549618/ – Artem Sokolov Mar 31 '10 at 02:45
  • Who says there is a virtual table? The standard says nothing about them and as such they are a figment of peoples imagination :-) If you want compiler specific implementation details you need to mention the compiler you are using. – Martin York Mar 31 '10 at 07:11

4 Answers4

16

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
nitin_cherian
  • 6,405
  • 21
  • 76
  • 127
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
2

Each class has its own vtable. The entry for f in Base will be NULL, and the entry in Derived will be a pointer to the code for the implemented method.

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
  • 1
    Well, not really NULL. In VC++ the entry is the address of the CRT function _purecall: http://thetweaker.wordpress.com/2010/06/03/on-_purecall-and-the-overheads-of-virtual-functions/ – Ofek Shilon Jun 13 '10 at 21:44
1

The vtable entry will be in the base class.

Why? Because you can have a base pointer type that holds a derived type object's address and still call the method on the base type's pointer variable.

Pure virtual simply tells the compiler that the derived types must provide their own implementation, and they cannot rely on the base class' implementation (if one is even specified in the base class)

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
1

In both actually. The base class vtable will have a slot for the pure virtual function pointing to something like pure_virtual_function_called() stub that would probably abort the program, while the derived class vtable will have a pointer to the actual implementation.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171