tags:

views:

63

answers:

1

Using VC8, I create two modules similar to the following:

Header

class IFoo
{
    virtual void Bar() = 0;
};

Module A

extern IFoo& Foo;

void DoStuff()
{
    Foo.Bar();
}

Module B

IFoo& Foo = ConcreteFoo();

VC8 handles this by essentially treating 'Foo' as a pointer to an IFoo. Wherever it sees Foo.Bar() (even in module B), it derefences the pointer to get the object's vtable, looks up the address of Bar() and calls it. This is a little irritating since Foo does in fact refer to a concrete object and always will. It would be nice if you could do something like the following:

Module A

extern __concrete IFoo& Foo;

This would tell the compiler that you promise to provide a concrete object to back this reference. It could then generate a special external reference to Foo.Bar() and directly call the method without the double dereferencing.

As far as I can tell, there's no way to do this with Visual C++, which leads to two questions:

  1. Is there a way to get the VC compiler to generate the direct method call?
  2. Are there any other C++ compilers that can do it?
+3  A: 
  1. Don't worry about one tiny little vtable lookup, unless profiling indicates that it's a bottleneck. (Hint: it probably won't be.)
  2. How should the compiler know what the concrete return type of ConcreteFoo() is going to be? If Foo::Bar() is virtual, the compiler cannot create a static call to Foo.Bar() because Foo's type is unknown at compile time.
  3. If you know the actual type of Foo, say Biz, you can do away with the reference:

    Module A

    extern Biz Foo;
    

    Module B

    Biz Foo = ConcreteFoo();
    

    (assuming that Biz has a copy constructor.)

Thomas
Peter Ruderman
Well, it already knows there *will* be a concrete impl, just not which one. It could be a class that uses multiple inheritance to give a stark example. This is key to OOP, there would be no polymorphism without this.
Hans Passant
Not necessarily. It might end up being assigned a reference to an IFoo; that's why the compiler would need an extra hint.
Peter Ruderman