I've stored hearing this statement. Switch..Situation is Evil for code maintenance, however it provides better performance(since compiler can inline things etc..). Virtual functions are extremely great for code maintenance, however they get in a performance penalty of two pointer indirections.

Say i've got a base class with 2 subclasses(X and Y) and something virtual function, so you will see two virtual tables. The item includes a pointer, according to so it will select a virtual table. So for that compiler, it's a lot more like

switch( object's function ptr )

   case 0x....:



   case 0x....:


Why should virtual function are more expensive, whether it could possibly get implemented by doing this, because the compiler can perform exactly the same in-lining along with other stuff here. Or explain me, why do made the decision to not implement the virtual function execution in by doing this?

Thanks, Gokul.

The compiler can't do this due to the separate compilation model.

At that time the virtual function call has been put together, there's not a way for that compiler to understand without a doubt the number of different subclasses you will find.

Think about this code:

// base.h
class base
    virtual void doit();


// usebase.cpp
#include "base.h"

void foo(base &b)

Once the compiler is producing the virtual get in touch with foo, it's no understanding which subclasses of base will exist at runtime.

Your question rests on misconceptions concerning the way switches and virtual functions work. Instead of fill this box having a lengthy treatise on code generation, I'll provide a couple of summary sentences:

  • Switch claims aren't always faster than virtual function calls, or inlined. Discover more about the way in which switch claims are converted into set up here and here.
  • The one thing that's slow about virtual function calls is not the pointer searches, it is the indirect branch. For complicated reasons having to do with the internal electronics of the CPU, for many modern processors it's faster to carry out a "direct branch", in which the destination address is encoded within the instruction, than an "indirect branch", in which the address is calculated at runtime. Virtual function calls and enormous switch claims are often implemented as indirect branches.
  • Inside your example above, the switch is totally redundant. Once an object's member function pointer continues to be calculated, the CPU can branch right to it. Even when the linker was conscious of every possible member object that been around within the executable, it might be unnecessary to include that table research.

There's no branching in virtual dispatch. The vptr inside your class indicates a vtable, having a second pointer for that specific function in a constant offset.