I’m writing a game in C++ that has about 30 different roles that are each slightly different. I have a main class User that contains all of the data required by all of the roles. My first implementation involved just having an enumeration of 30 roles and handling appropriately, but now I’m wondering if it would be better to have User as a base class and each role being its own class that inherits from User.
My main concern is how efficient are polymorphic method calls when there are 30+ classes inheriting from a single base class? I know polymorphic calls involve pointers in a virtual table but I’m not sure if that means a linear search through the entire table for the right method or if it can be done in constant time.
If anyone could comment on the efficiency of polymorphic method calls with a many inherited classes I would appreciate the enlightenment.
Thanks in advance!
The cost is negligeable. It doesn’t matter how many classes you have, or how many levels of inheritance, the cost of a polymorphic call is a simple addition – the pointer to the
vftableplus the offset of the specific function (not standard mandated, but on most, if not all, implementations this is correct).