tags:

views:

500

answers:

4

Where in memory is vtable stored?

+4  A: 

Depends on compiler.

In VC++, the vtable pointer stored at the beginning of the object allocation, before any member data. (Provided your class has at least one virtual member function.)

There also may be multiple vtable pointers, if your class multiply-inherits from other classes with vtables.

The vtables themselves are statically allocated somewhere in your address space.

Then the object layout looks like (for an instance of C):

A's VTable ptr
A's member variables.
B's Vtable ptr
B's member variables.
C's member variables.

for the heirarchy

class A {
  virtual Ax() {}
  int a, b;
};
class B {
  virtual Bx() {}
  int c, d;
};
class C : public A, public B {
  int foo, bar;
};
Alex
I think you're talking about vptr's, that is, pointers to vtables. Vtables themselves are generally stored in the static data segment, as they are class-specific (vs. object-specific).
Drew Hall
Indeed, I amended my post :)
Alex
The object layout is for an instance of C, right? (As opposed to an A, a B and a C)
Niklas
Yes, for a C instance.
Alex
+3  A: 

For VC++

nico
A: 

The vptr commonly at the beginning of the object (Imperfect C++, Backyard Hotrodding C++) but that's not guaranteed in the standard. Using vptrs and vtables isn't guaranteed in the standard.

If you really need to know where it is, it's common to use something like COM, XPCOM, UNO, etc. that are implemented by essentially coming up with a set place where something like a vptr is located and set ways to use them.

Max Lybbert
CM and CORBA C++ bindings that I've used leave the placement of the vtable up to the C++ compiler.
anon
Thanks, I've removed CORBA from the list
Max Lybbert
+3  A: 

Vtable? What vtable? The C++ standard doesn't mention a vtable. Each compiler can implement virtual functions any way it likes. And that includes placing the vtable anywhere it likes.

jalf
I believe that the vtable can be anywhere except at the starting address of the object. My understanding is that the address of the first element is also the starting address of the structure.
Thomas Matthews
No, that's not a requirement. It is the case for POD types, but POD types don't have a vtable, so it's a non-issue there. For non-POD types, there's no guarantee that the address of the structure is the same as the address of the first element.
jalf