Thread: Virtual function optimization

  1. #1
    Registered User
    Join Date
    Dec 2006

    Virtual function optimization

    I'd like to know if compilers can optimize the following code. I'm interested in MSVC++ and g++.

    class Base
       virtual void doSomething() = 0;
    class Derived : public Base
       void doSomething() { whatever; }
    int main()
       Derived* d = new Derived();
       d->doSomething(); // Will this be called through the vtable?
       // What if the object is on the stack?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    It the code-sequence is such that the compiler can figure out which function will be called, it will not go via the vtable, as that's just unnecessary work [unless you plan on "editing" the vtable - but that's naughty stuff].

    The question then becomes "how complex things can the compiler figure out", and there is no real simple answer to that - I've seen it do some pretty amazing stuff, but at other times, it's not quite so clever. Realisticly, if there is any condition that may lead to a "different" result, then the compiler will take the safe option and use the vtable.

    In the above listed example, I'm pretty sure that it will call directly to Derived::doSomething().

    If the object is directly created on the stack [rather than a pointer to an object on the stack] then I'm sure the compiler will know the function and not call via the vtable. There is absolutely no reason why the compiler shouldn't be able to figure this out correctly.

    [Of course, if you compile with "-O0" [no optimisation] then the compiler will most likely not perform even such trivial optimization.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-28-2009, 09:25 AM
  2. Stroustrup Talk on C++0x
    By jverkoey in forum A Brief History of
    Replies: 19
    Last Post: 07-20-2007, 02:02 AM
  3. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM