pankajt
pankajt

Reputation: 7864

Virtual Table layout in memory?

how are virtual tables stored in memory? their layout?

e.g.

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

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

How will be the layout of virtual tables of class A and class B in memory?

Upvotes: 14

Views: 23238

Answers (6)

linuxbuild
linuxbuild

Reputation: 16133

For GCC compiler in Linux run:

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

NOTE: Before GCC 8, the option is -fdump-class-hierarchy instead of -fdump-lang-class.

The output is:

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)

Also I've created the vtable-dumper tool to list contents of virtual tables in the shared objects. With this tool you don't need to compile headers, just run it on the object:

vtable-dumper SHLIB

Upvotes: 39

sbi
sbi

Reputation: 224049

As others already wrote, there is no general approach. (Heck, nobody even mandates that virtual tables are used at all.)

However, I believe they are most likely implemented as a hidden pointer at a certain offset in the object which references a table of function pointers. Certain virtual functions' addresses occupy certain offsets in that table. Usually there's also a pointer to the dynamic type's std::type_info object.

If you're interested in things like this, read Lippmann's "Inside the C++ Object Model". However, unless your interest is academic (or you're trying to write a C++ compiler -- but then you shouldn't need to ask), you shouldn't bother. It's an implementation detail you don't need to know and should never rely on.

Upvotes: 4

cmeerw
cmeerw

Reputation: 7356

For a very detailed description of Open Watcom's class layout have a look at the Class Layout notes

Upvotes: 1

anon
anon

Reputation:

As others have said, this is compiler dependant, and not something that you ever really need to think about in day-to-day use of C++. However, if you are simply curious about the issue, you should read Stan Lippman's book Inside the C++ Object Model.

Upvotes: 13

Naveen
Naveen

Reputation: 73443

From wikipedia:

The C++ standards do not mandate exactly how dynamic dispatch must be implemented

So the answer is no. Layout of vtable is implementation defined.

Upvotes: 3

DarkSquid
DarkSquid

Reputation: 2656

vtable layout in memory is completely compiler dependent; there's no "correct" or universal approach taken.

Upvotes: 6

Related Questions