3

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

M-R
  • 227
  • 2
  • 9
  • 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 '16 at 00:09

1 Answers1

4

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.

Mike Dunlavey
  • 12,815
  • 2
  • 35
  • 58
  • 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 '16 at 14:09
  • @gnasher729: Good point. So edited. – Mike Dunlavey Sep 18 '16 at 14:28