Search code examples
c++code-organization

Avoiding virtual functions


So suppose I want to make a series of classes that each have a member-function with the same thing. Let's call the function

void doYourJob();

I want to eventually put all these classes into the same container so that I can loop through them and have each perform 'doYourJob()'

The obvious solution is to make an abstract class with the function

 virtual void doYourJob();

but I'm hesitant to do so. This is a time-expensive program and a virtual function would slime it up considerably. Also, this function is the only thing the classes have in common with each other and doYourJob is implimented completely differently for each class.

Is there a way to avoid using an abstract class with a virtual function or am I going to have to suck it up?


Solution

  • Virtual functions don't cost much. They are an indirect call, basically like a function pointer. What is the performance cost of having a virtual method in a C++ class?

    If you're in a situation where every cycle per call counts, that is you're doing very little work in the function call and you're calling it from your inner loop in a performance critical application you probably need a different approach altogether.