[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.16 Virtual Tables

In order to invoke virtual functions, GNU C++ uses virtual tables. Each virtual function gets an index, and the table entry points to the overridden function to call. Sometimes, and adjustment to the this pointer has to be made before calling a virtual function:

 
struct A{
  int i;
  virtual void foo();
};

struct B{
  int j;
  virtual void bar();
};

struct C:A,B{
  virtual void bar();
};

void C::bar()
{
  i++;
}

int main()
{
  C *c = new C;
  B *b = c;
  c->bar();
}

Here, casting from `c' to `b' adds an offset. When `bar' is called, this offset needs to be subtracted, so that `C::bar' can properly access `i'. One approach of achieving this is to use thunks, which are small half-functions put into the virtual table. The modify the first argument (the `this' pointer), and then jump into the real function.

The other (traditional) approach is to have an additional integer in the virtual table which is added to this. This is an additional overhead both at the function call, and in the size of virtual tables: In the case of single inheritance (or for the first base class), these integers will always be zero.



This document was generated by system on December, 2 2004 using texi2html