Search code examples
c++virtual

Virtual Function Implementation


I have kept hearing this statement. Switch..Case is Evil for code maintenance, but it provides better performance(since compiler can inline stuffs etc..). Virtual functions are very good for code maintenance, but they incur a performance penalty of two pointer indirections.

Say i have a base class with 2 subclasses(X and Y) and one virtual function, so there will be two virtual tables. The object has a pointer, based on which it will choose a virtual table. So for the compiler, it is more like

switch( object's function ptr )
{

   case 0x....:

       X->call();

       break;

   case 0x....:

       Y->call();
};

So why should virtual function cost more, if it can get implemented this way, as the compiler can do the same in-lining and other stuff here. Or explain me, why is it decided not to implement the virtual function execution in this way?

Thanks, Gokul.


Solution

  • The compiler can't do that because of the separate compilation model.

    At the time the virtual function call is being compiled, there is no way for the compiler to know for sure how many different subclasses there are.

    Consider this code:

    // base.h
    class base
    {
    public:
        virtual void doit();
    };
    

    and this:

    // usebase.cpp
    #include "base.h"
    
    void foo(base &b)
    {
        b.doit();
    }
    

    When the compiler is generating the virtual call in foo, it has no knowledge of which subclasses of base will exist at runtime.