Virtual functions realize polymorphism. I do not know Obj-C, so I can not compare both, but the motivating use case is that you can use derived objects instead of base objects, and the code will work. If you have a compiled and working foo function that works with a base reference, you don’t need to modify it to work with the derived instance.
You can do this (provided that you had information about the type of runtime) by getting the actual type of the argument and then sending the corresponding function directly using the short circuit switch, but for this you will need to either manually change the switch for each new one (high cost servicing) or the presence of reflection (not available in C ++) to get a method pointer. Even then, having received a method pointer, you will have to call it, which is as expensive as a virtual call.
As for the cost associated with a virtual call, basically (in all implementations with a table of virtual methods), a call to the virtual function foo , applied to the object o : o.foo() , translates to o.vptr[ 3 ]() , where 3 is the position of foo in the virtual table, and this is the compile-time constant. This is basically a double direction:
From the o object, get a pointer to a vtable, index this table to get a pointer to a function, and then call it. The extra cost compared to a direct non-polymorphic call is just a table search. (Actually, there may be other hidden costs when using multiple inheritance, since the implicit this pointer may be biased), but the cost of virtual sending is very small.
David Rodríguez - dribeas
source share