Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many vtable and vpointers will be created in this example? [closed]

Tags:

c++

vptr

Here is the program on vtables. Am I understanding is correct on vtables and v-pointers.

Class B
{
  public:

  virtual Void Hello()
  {
    cout<<"Hello Base";
  }
};

class D: public B    
{
  public:

  virtual void Hello()
  {
    cout<<"Hello Derived";
  }
};

int main(int argc, char* argv[])
{
  D *d1 = new D();
  D *d2 = new D();
  D *d3 = new D();

  return 0;
}

In my opinion, there will be two vtables and only one vptr. Am I correct on it?

like image 366
dexterous Avatar asked Apr 19 '14 12:04

dexterous


People also ask

How many vtable are there?

one vtable per class, containing the virtual function pointers and other metadata for that class; one vptr per object, pointing to the vtable for that object's dynamic class type.

How many vtable will be created in following code?

The answer is 3 virtual tables.

How many VPTR are created in C++?

There is only one VPTR for each object when using simple inheritance like this. The VPTR must be initialized to point to the starting address of the appropriate VTABLE. (This happens in the constructor, which you'll see later in more detail.)

How many virtual tables are created?

Basically, 2. One for class A , one for class B (vftables) and 2 vfptrs, one for a1 and one for b1 . However, this is not standard mandated, so you could as well have none. (usually implementations use vftables, but its not mandated.


1 Answers

The standard does not define how virtual functions are actually implemented, only how they should behave. So what you are asking for entirely depends on the compiler you are using.


GCC will in theory most likely create two vtables (one for B and one for D) and three vptrs (one for each of the object instances d1, d2, d3).

Have a look here: http://en.wikipedia.org/wiki/Virtual_method_table

like image 159
Danvil Avatar answered Oct 04 '22 17:10

Danvil