1

What is a V-Table, what does it do? From my understanding, it stores function pointers, but why? Why wouldn't the compiler just copy-paste the parent functions into the current class?

For example, with the parent class:

#include <iostream>

class ParentClass
{
public:
  int parentState;
  virtual void func()
  {
    parentState = 1;
    std::cout << "Parent Function: " << parentState << std::endl;
  };
};

And a child class:

#include <iostream>

class ChildClass : public ParentClass
{
public:
  void func()
  {
    parentState = 2;
    std::cout << "Child Function: " << parentState << std::endl;
  };
};

Why wouldn't the compiler just copy-paste everything from the parent class except the things that are overridden? Like this:

#include <iostream>

// "Compiled" or "Behind the Scenes" Child Class
class ChildClass
{
public:
  int parentState;
  void func()
  {
    parentState = 2;
    std::cout << "Child Function: " << parentState << std::endl;
  };
};

I may be greatly misunderstanding how C++ inheritance works, but it seems strange to me that a V-Table is even required. I have also heard that V-Tables are not the most performant thing, is this true?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • As I understand it, for each class there is a table of function pointers. Each instance has exactly one pointer as part of its size that points to the table corresponding to its type. – Ben Dec 12 '21 at 00:51
  • If I'm not mistaken, the V table allows run-time determination of which function to run in order to allow parent-child class polymorphism, again, at run time. – Gabriel Staples Dec 12 '21 at 00:52
  • ...But this is probably duplicate question and probably has some answers elsewhere on the site already. Do a thorough search on stack overflow and see what you find. – Gabriel Staples Dec 12 '21 at 00:53
  • Vtables aren't inherently required by the c++ standard, they are just an option amongst others to implement polymorphism in object oriented class hierarchies. – πάντα ῥεῖ Dec 12 '21 at 00:54
  • *"Why wouldn't the compiler just copy-paste everything from the parent class except the things that are overridden?"* -- This is reasonably accurate (compilers do basically copy-paste the parent definition into the child, with caveats), yet this has nothing to do with why vtables exist. Hence your confusion. Sometimes it pays to step back and question your assumptions (or to look for assumptions that you were not aware of). – JaMiT Dec 12 '21 at 01:19
  • The answer is: to suport inheritance, method Overriding and polymorphism. – Adriel Jr Dec 12 '21 at 01:37

0 Answers0