Suppose we have a base class A
and 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...?
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– gnasher7292016年09月18日 14:09:10 +00:00Commented Sep 18, 2016 at 14:09
-
@gnasher729: Good point. So edited.Mike Dunlavey– Mike Dunlavey2016年09月18日 14:28:39 +00:00Commented Sep 18, 2016 at 14:28
Explore related questions
See similar questions with these tags.
A
, would typically not be involved in method invocations on aB
instance. When a client invokesA::foo
, on aB
instance,B
's vtable alone is sufficient to direct execution toB::foo
. When theB::foo
implementation invokes its parentA::foo
, this is a direct call bypassing virtual dispatch (so here neitherA
's norB
's vtable is accessed).