简体   繁体   中英

C++ vptr is duplicated in every object

In c++, we have VPTR in every object, but only one VTABLE per class. Why VPTR is in every object? isnt it duplication?

If you have:

class base
{
   virtual void func() = 0; 
}

class a: public base
{
 public:
   virtual void func() { cout << "a" << endl; }
}

class b: public  base
{
 public:
   virtual void func() { cout << "b" << endl; }
}


void call_func(base *x)
{
    x->func();
}

int main()
{
    vector<base *> v;

    v.push_back(new b);
    v.push_back(new a);

    for(int i = 0; i < v.size(); i++)
        call_func(v[i]);
}

How does "call_func" know which one of the func to call?

It turns out that it uses the vtable (vptr) to find the func to call.

[Yes, the code is a giant memory leak - I'm trying to keep it simple]

How else will an instance of C++ object in memory refer to its VTABLE? However, VPTR-VTABLE is compiler specific implementation, C++ standard doesn't say anything about it. Usually, it is the first (hidden) member of an instance of polymorphic class.

It comes with a cost as having such hidden members makes the C++ memory model incompatible with C. It is an overhead, AGREED, but there is no other(better) ways of referring to a VTABLE from an instance of C++ object in memory.

Without runtime type information you do not know which class an object is in. So in order to call methods you would need to store the class info, and then use that to lookup the correct vtable to call. It is easier (and more direct) to just put a pointer into every object.

First of all, nothing of this is guaranteed by the standard and you would need to talk about a specific compiler to get specific answers.

Dynamic binding works on the object level. A class is never used polymorphically, an object is. So you will need to figure out how a certain function is bound on a per object basis.

That pointer is the only way to identify an object's type. It is necessary for each object to have one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM