Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of virtual table [duplicate]

Tags:

c++

gcc

g++

vtable

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.

like image 657
Anon Avatar asked Oct 27 '12 12:10

Anon


1 Answers

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.

like image 181
Appleman1234 Avatar answered Sep 19 '22 09:09

Appleman1234