A question about virtual function

As I know, there's a virtual function table with a class type(contain virtual funcion). And there's pointer point to this talbe in a class.
My question is How does the function find the virtual function in this talbe, like:
1
2
3
4
5
6
7
8
9
10
class A
{
    virtual fun1() {};
    virtual fun2() {};
}

class B:public A
{
    virual fun1() {};
}


the B virtual table like:
B::fun1()
A::fun2()

And when I declare B like A *a = new B;
there's a pointer
__vfptr
point to B talbe in a;
and when i call a->fun1() How the programme find fun1 from table?(I mean it find fun1 neither fun2) Is it decide by the compiler?

Hope you know what I mean, thank u.
Internally the compiler assigns "indices" to each virtual function it finds.

When the compiler parses class A's declaration, it assigns fun1 index 0 and fun2 index 1.
When the compiler parses class B's declaration, there are no new virtual functions (just overridden ones),
so no new indices are allocated.

Therefore, when the compiler compiles a->fun1(), the compiler knows that the index of fun1 is 0, so it
looks in the 0th entry in the vtable.


Emm...you mean there's one table nor 2 talbes?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class A 
{
    virtual fun1() {};
    virtual fun2() {};
    virtual fun3() {};
}

class B:public A
{
    virtual fun1() {};
    virutal fun4() {};
}

class C:public B
{
   virtual fun1() {};
   virtual fun4() {};
}

int main(int args, char *arg[])
{
    A *p = new C();
    p->fun1();
}

In this case, how the c->fun1() to be found?
Last edited on
Topic archived. No new replies allowed.