Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of the virtual table important?

Tags:

c++

I'm new so go easy on me :) From what my lecturer had told some time ago, the order of the virtual table is important. But I do not understand the reason for that!!?

Given the next code :

class A
{
public:
    A() {cout <<"1" << endl;};
    A (const A& s) {cout << "2" << endl;}
    ~A () {cout << "3" << endl;}
    void f1() {cout << "4" << endl; f2();}
    virtual void f2() = 0;
    virtual void f3() {cout << "5" << endl;}

};


class B : public A
{
public:
    B() {cout << "6" << endl;}
    B(const B& b) : A(b) {cout << "7" << endl;}
    ~B() {cout << "8" << endl;}

    virtual void f1() {cout<<"9"<<endl;}
    void f2() {cout<<"lO"<<endl; f4();}
    virtual void f2(int i) {cout << "11" << endl;}
    virtual void f4() {cout << "12" << endl; f3();}

};

He said that the order is :

A's vtable : 
A::f2()
A::f3()

B's vtable : 
B::f2()
A::f3()
B::f1()
B::f2(int)
B::f4()

But I don't understand why it is important? He said that the vtable is useless if it's not by its correct order, can you please explain why?

like image 830
Ron_s Avatar asked Aug 26 '11 16:08

Ron_s


2 Answers

There is no notion of vtables in the C++ standard. It's just that most implementations (if not all) use it for virtual dispatch. The exact conventions, however, are totally implementation-defined.

That said... The order of the functions is important, but not for the programmer, but for the compiler - you can arrange your functions however you want in your code. The compiler, however, will typically put each function pointer into a specific place in the vtable, which it has dedicated to that function. So that when it needs to call f() it knows the index of the f() function and takes that pointer from the vtable.

This question might help you as well: Virtual dispatch implementation details

like image 115
Armen Tsirunyan Avatar answered Sep 21 '22 14:09

Armen Tsirunyan


The order of the vtable is important for things to work properly, but only to the compiler (i.e. you don't need to care because it takes care of it).

If the compiler put it out of order for itself, then yeah, things would break, because functions are looked up by offset (so an offset would yield a random function which would be catastrophic).But the average programmer doesn't need to worry about what order the vtable is in.

like image 34
Seth Carnegie Avatar answered Sep 21 '22 14:09

Seth Carnegie