开发者

Relation between 'This' Pointer and Vtable Functions

I do not have much idea about the functionality of the Virtual Table, but in the code pasted below - the this pointer passed is obviously points to different locations in the 2 cases - but the function show() in the memory - is it instantiated/meaning created separately for every object at Runtime? (Forgive my poor understanding of C++ jargons)

#include<iostream>
using namespace std;
class A
{
      int x;
      public:
            A(){x=0;}
            A(int z){x=z;}
            void show()
            {  
                 if(x==0)
                 cout<<"\nCalled by OBJ_1";
                 else
                 cout << "\nCalled by OBJ_2";
            }
};

int main()
{
 A OBJ_1,OBJ_2(1);
 OBJ_1.show();
 OBJ_2.show();
}

If an example (with some memory-diagrams if possible) could be provided regarding how the Virtual Table works and the functionality of the this pointer 开发者_JS百科w.r.t Virtual Table could be explained, i would much appreciate it.


A does not have a vtable at all (or it shouldn't on any good compiler) because it is not a polymorphic class: it has no virtual member functions.

The function show() exists in the executable exactly once. Member functions aren't really different from ordinary nonmember functions, they just have an extra, implicit this parameter. You can think of it as if the compiler transforms a member function into a similar nonmember function, for example:

void show(A* this)
{
    if (this->x == 0)
        cout << "\nCalled by OBJ_1";
    else    
        cout << "\nCalled by OBJ_2";  
}

Instead of OBJ_1.show(), the comparable way to call this nonmember function would be to use show(&OBJ_1).

There isn't one A::show() per A object that is created. There's one A::show() total and it takes as an argument the instance on which it was called.


C++ standard doesn't define the term "virtual table" explicitly. An implementation is free to implement a polymorphic class (a class which has at least one virtual function) in any way it wants. But most common implementations use a v-table with v-ptr.

Check out what Marshall Cline has to say about virtual functions


No, there is only one copy of the code corresponding to each function (member or non-member). The function uses the this pointer to determine which object to actually operate on.

You don't have any virtual methods so there's no vtable in your code at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜