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

StackOverflow https://stackoverflow.com/questions/23170175

  •  06-07-2023
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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

Outras dicas

You might find the implementation detail in your compiler documentation. It may vary from version to version, even between platforms.

For gcc on Linux, it is likely that each D instance will need its vptr and one vtable.

You have 3 instances of D:

  • Each will have its vptr -> 3 vptr
  • Each points to the same vtable.

So 3 vptr and 1 vtable (+1 vtable for B, which is useless here).

Again this is an implementation detail, and in your very simple case it is subject to compiler optimisations.

In a typical vtable-based implementation of virtual polymorphism, there will be:

  • 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.

So here there will be two vtables (for B and D) and three vptrs (in *d1, *d2 and *d3). Unless the compiler notices that you're not using the objects an eliminates them altogether.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top