linking virtual members

Started by
1 comment, last by antareus 19 years, 9 months ago
I'm not sure on how virtual members work, but could you do something like this?:
//MyDll.cpp

class __declspec(dllexport) CMyClass
{
public:
    virtual void DoSomething() { }
};

__declspec(dllexport) void MakeCall(CMyClass *o)
{
    o->DoSomething();
}

//MyExe.cpp

class __declspec(dllimport) CMyClass
{
public:
    virtual void DoSomething();
};

__declspec(dllimport) void MakeCall(CMyClass *o);

class CMySubClass : public CMyClass
{
public:
    virtual void DoSomething();
} *MyObj;

MakeCall((CMyClass*)MyObj);
I exported a class from a DLL, made a subtype of this class in the EXE, and made a call to a function in the DLL that makes a call to a virtual member function of the origonal class. Will it make a call to the CMySubClass's version of the function? BTW: Sorry if I'm unclear (I usually am).
------------------------------------------------------------"Many combilations elizagerth. I hope you see my particles." - Senor Cardgage
Advertisement
In theary, it will call the virtual member function of the derived class, CMySubClass.

Kuphryn
Yes, I do this all the time. Be careful of the fragile base class problem; that is, whether the base class has changed between the time the EXE was built and the DLL was linked. It is possible to link the two when one is using an old definition, and the vtable layout won't match up.

If this turns out to be a problem I think you can safely add virtual member functions to the end of the base class definition and DLLs using older versions of the base class should still call the correct ones. Since the vtable is laid out sequentially, this makes sense. However none of this is guaranteed by Ye Holy Standard, it is more a by-product of common implementation details.

And the base cast is doesn't need to be explicitly specified.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis

This topic is closed to new replies.

Advertisement