Search code examples
c++com

Adding "normal" class member to COM class


I've got a question about some practices related to COM. Is it good/normal practice to have a COM class and in it have a member that's a normal/regular class?

Here's a short example of what I mean:

// in myClass.h
class MyClass
{
    // constructors, members etc.
};


// in myCOMClass.h
#include "myClass.h"
class IMyCOMClass : public IUnknown
{
    // AddRef & co. etc.
    protected:
        MyClass _m;
};

Is the above code acceptable or is it bad practice and unadvised?


Solution

  • That's perfectly fine and advisable, due to future-proofing and build times:

    Ideally you want to put as small amount of functionality in the COM class as possible. This is to facilitate porting your code to other interfacing classes (e.g. JNI for Java, XLL for Excel etc). I've seen some COM interfaces that use the pImpl idiom to abstract completely the functionality away from the COM classes.

    It can also help build times too: a change in the IDL will force a recompilation of all compilation units that include the automatically-generated COM headers. This can get quite tedious for large COM libraries.

    In your case that would mean having MyClass* _m as the data member and using a forward declaration in the header.