Tag: virtual functions

Virtual functions in C++ – thoughts on performance penalty

Most C++ developers have heard about performance penalty of using virtual functions. But is it really so high that you should avoid this useful and sometimes the only possible language feature for a particular case?

First let’s see when this feature is really needed. When you wish to write a testable code, you likely have to deal with some sort of dependency injection.

Let’s say you have some class:

class SomeNastyBigClass
    m_dependency1(param1, param2, param3),
    m_dependency2(param1, param2, param3),
    m_dependency3(param1, param2, param3)
    // some other work for dependencies initialization

  // lots of different methods

  SomeDependencyClass1 m_dependency1;
  SomeDependencyClass2 m_dependency2;
  SomeDependencyClass3 m_dependency3;

Continue reading “Virtual functions in C++ – thoughts on performance penalty”