Search code examples
c++windowspure-virtuallate-binding

Does a pure abstract C++ class declared in a header used in different projects (without compile time linking) share the same Virtual Table model?


I have a C++ header declaring a class composed of pure virtual methods only. I have two DLLs using that header, (with one implementing that interface) but not linked at compile time. One DLL is loading the other one dynamically, passing a pointer of the implemented interface to the other. Are these DLL's sharing the same virtual table structure?


Solution

  • You're safe.

    The order in which the methods appear in the vftable is determined by the base class structure, and that's all you should care about. But this is compiler specific, so use the same compiler for generating the dll's. Don't rely on them being backward-compatible (or at least check the documentation).

    Assume you have the following header:

    //header.h
    
    class A
    {
    public:
        virtual void foo() = 0;
        virtual void goo() = 0;
    };
    

    And you have B.dll with the following class:

    class B : public A
    {
    public:
        virtual void foo() {}
        virtual void goo() {}
    }
    

    Now, in X.dll, you receive a pointer to an A that is a B object created in B.dll.

    The call

    void test( A* a )
    { 
       a->foo();
    }
    

    will invoke B::foo().

    One neat experiment you can try is to compile B.dll with header.h and when you compile X.dll, invert the order of the methods in header.h:

    //header.h
    
    class A
    {
    public:
        virtual void goo() = 0;
        virtual void foo() = 0;
    };
    

    In this case, although you should never do this, the same call to test() in X.dll will probably call the method B::goo(). That is because X.dll assumes the vftable present in the header. It's undefined behavior though; I just wrote this example to make a point.