Suppose we have a base class Aand derived class B. A implements a virtual method foo() which is overloaded in B.

If we have an object test of type B, then the object would surely contain both implementations of foo(). When we call the method, how is the correct (most derived) method found?

Would the vptr contained in the base class come into use perhaps...?

  • In C++ the vtable for the base class, A, would typically not be involved in method invocations on a B instance. When a client invokes A::foo, on a B instance, B's vtable alone is sufficient to direct execution to B::foo. When the B::foo implementation invokes its parent A::foo, this is a direct call bypassing virtual dispatch (so here neither A's nor B's vtable is accessed).
    – Erik Eidt
    Sep 19, 2016 at 0:09

1 Answer 1


If a function/method is virtual, that means the object has a table of pointers, and one of them points to that function. (As @gnasher729 pointed out, that table is shared among all instances of a class, so it takes minimal space.)

If B does not override the function, then the table points to A's version of the function.

If A defines the function as pure virtual, then B has to override it, because A has no definition for the function.

  • Actually, since you don't want that table duplicated for all the instances of one class, the compiler builds the table for one class in memory once, and each instance of the class holds just a pointer to the same table. There's another table in memory for the subclass, and each instance of the subclass holds a pointer to the table for the subclass.
    – gnasher729
    Sep 18, 2016 at 14:09
  • @gnasher729: Good point. So edited. Sep 18, 2016 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.