Virtual table layout in memory?

How are virtual tables stored in memory? their location?

eg.

class A{ public: virtual void doSomeWork(); }; class B : public A{ public: virtual void doSomeWork(); }; 

What will be the location of the virtual tables of class A and class B in memory?

+6
c ++ vtable
source share
6 answers

As others have said, it depends on the compiler, not what you really need to think about in everyday use of C ++. However, if you are just curious about this problem, you should read Stan Lippman's book Inside the C ++ Object Model .

+10
source share

For the GCC compiler on Linux, run:

 g++ -fdump-class-hierarchy example.h 

Output:

  Vtable for a
 A :: _ ZTV1A: 3u entries
 0 (int (*) (...)) 0
 8 (int (*) (...)) (& _ZTI1A)
 16 (int (*) (...)) A :: doSomeWork

 Class a
    size = 8 align = 8
    base size = 8 base align = 8
 A (0x7fb76785a4e0) 0 nearly-empty
     vptr = ((& A :: _ ZTV1A) + 16u)

 Vtable for b
 B :: _ ZTV1B: 3u entries
 0 (int (*) (...)) 0
 8 (int (*) (...)) (& _ZTI1B)
 16 (int (*) (...)) B :: doSomeWork

 Class b
    size = 8 align = 8
    base size = 8 base align = 8
 B (0x7fb7678510d0) 0 nearly-empty
     vptr = ((& B :: _ ZTV1B) + 16u)
   A (0x7fb76785a540) 0 nearly-empty
       primary-for B (0x7fb7678510d0)

I also created the vtable-dumper tool to display the contents of virtual tables in shared objects. With this tool, you do not need to compile the headers, just run it on the object:

 vtable-dumper SHLIB 
+25
source share

The vtable format in memory depends entirely on the compiler; there is no β€œright” or universal approach.

+6
source share

From wikipedia :

C ++ standards do not provide for how dynamic dispatch should be implemented

So the answer is no. The vtable layout is determined by the implementation.

+3
source share

As others have already written, there is no general approach. (Hell, no one even requires virtual tables to be used at all.)

However, I believe that they are most likely implemented as a hidden pointer with a specific offset in an object that refers to a table of function pointers. Some virtual function addresses occupy specific offsets in this table. Usually there is also a pointer to an object of dynamic type std::type_info .

If you are interested in such things, read Lippmann's "Inside the C ++ Object Model" . However, if your interest is not academic (or you are trying to write a C ++ compiler), but then you do not need to ask), you should not worry. This is an implementation detail that you don’t need to know and should never rely on.

+3
source share

For a very detailed description of the Open Watcom class, consider the layout of the class notes.

+1
source share

All Articles