tags:

views:

496

answers:

5

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?

+5  A: 

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

DarkSquid
how do standard compilers like gcc and visual studio store them?
Devil Jin
Wikipedia ( http://en.wikipedia.org/wiki/Virtual_method_table ) uses g++ as an example when describing vtable layout.
Tyler McHenry
+2  A: 

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.

Naveen
"The answer is no"? It wasn't a yes/no question.
Rob Kennedy
I'd say, given "Virtual Table layout in memory?", this is open for different opinions. `:)`
sbi
+2  A: 

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.

sbi
+6  A: 

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.

anon
A: 

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

cmeerw