2

What is the use of vtable (or why is vtable required ) in case of virtual inheritance ? what does this vtable points to in this case.

example:

class A
{
    void show()
    { }
};

class B : virtual A
{
    void disp()
    { }
};

In the above example the size of class B is 8 bytes. which means class B has vptr pointing to a Vtable. What does this vtable point to .

sony
  • 59
  • 4
  • The C++ standard has nothing to say on the subject of vtables. As such, these notions are compiler-specific. Which compiler(s) have you tried this on? –  Jul 08 '17 at 19:04
  • 1
    GCC and Clang use it for typeinfo. – harold Jul 08 '17 at 19:06
  • 1
    A vtable consists of pointers to functions, so what it points to is blocks of machine code, basically. – melpomene Jul 08 '17 at 19:08
  • 2
    @melpomene, what OP is actually asking is: in the case of normal inheritance without any virtual functions, most compilers don't bother with a vtable. In this scenario, there are no virtual functions, yet there still is a vtable which is weird to him. –  Jul 08 '17 at 19:09
  • @Frank , Yes thats exactly my question. I have read that these vtable points to subobject of class A. Is that true? – sony Jul 08 '17 at 19:12
  • The vtable doesn't do much for a single class like this, but when you inherit from several classes all deriving from `A` they will need a way to find the single instance of their shared base class. – Bo Persson Jul 08 '17 at 19:16

1 Answers1

0

A vtable is the most common way of implementing the virtual keyword in C++ -- any class that uses the virtual keyword will have a vtable created for it and every instance of that class will contain a pointer to that (single) vtable. The vtable contains information on the dynamic class of the object (to support dynamic_cast and typeinfo) as well as information as to where virtual base classes and functions of the class are located.

In this specific case, the vtable for B will likely contain just dynamic class info, as A has no data members or virtual functions.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Note that you can only use `dynamic_cast` and `typeinfo` on polymorphic classes, not on classes with virtual bases like `B`, even though the underlying mechanism is fully present for such classes on many (but not all) compilers. – curiousguy May 04 '21 at 00:03