9

Possible Duplicate:
Understanding the vtable entries

Using g++ version 4.6.3, 64-bit machine . I know compiler is free to implement virtual functions any way it wants. I want to know what happened here.

My class:

#include <iostream>
class test
{
    public:
    virtual void func(){std::cout<<"in class test";}
};

int main()
{
    test obj;
    obj.func();
    return 0;
}

Looking at virtual table generated by compiler,

Vtable for test
test::_ZTV4test: 3u entries
0     (int (*)(...))0 (<---- what is this? )
8     (int (*)(...))(& _ZTI4test)
16    (int (*)(...))test::func

At offset 8 it is RTTI

At offset 16 it is entry for virtual function.

My question is why is there entry for NULL at offset 0 or in other words what is the purpose of first entry?

P.S. I thought this could be related to alignment, but then I added more virtual functions but RTTI entry was still at offset 8.

Community
  • 1
  • 1
Anon
  • 2,608
  • 6
  • 26
  • 38
  • I would guess it's reserved for the destructor (which you didn't add). – john Oct 27 '12 at 12:47
  • @John, added destructor still same output. Also, is is necessary destructor will always be part of v-table? – Anon Oct 27 '12 at 12:49
  • It's very common to have a virtual destructor if you have any virtual functions. But it's not required. Oh well my guess was wrong. – john Oct 27 '12 at 12:57
  • @Anon - Did you make sure to mark the destructor as virtual? John's explanation seems pretty reasonable, so I just wanted to double-check. – Xavier Holt Oct 27 '12 at 13:29
  • @XavierHolt , I did not initially but just tried as you and John suggested. RTTI is still at offset 8. – Anon Oct 27 '12 at 13:32
  • @Anon - Hmm. Dunno, then - good luck! – Xavier Holt Oct 27 '12 at 13:35

1 Answers1

9

I believe the first entry or the entry at 0 the is the offset to top pointer.

See the following relevant stackoverflow question

Looking through the remainder -fdump-class-hierarchy from your source code , most classes seem the have the first entry as (int (*)(...))0 , the only classes that don't have it as the first entry have it as the second and have the first entry as the offset to the parent class given the C++ STL class hierarchy for streams.

In the relevant question a dead link to some vtable examples is given, I believe a live version of that link is available here

Another useful resource detailing the structure of vtables is here.

Community
  • 1
  • 1
Appleman1234
  • 15,946
  • 45
  • 67
  • Yep. It's the "offset to top" pointer. Amongst other things, this is used to implement `dynamic_cast`. That cast gives a pointer to the most derived object. The standard of course doesn't say anything about vtables, or about how an implementation will go about making `dynamic_cast` function as required. – David Hammen Oct 27 '12 at 14:17