views:

13

answers:

1

I'm trying to create a COM Class Library for my VBA Project and one of the limitations I've seemed to have stumbled across is using constructors on the New() subroutine. After creating the new COM class a Public Sub New() is created with the following comments

' A creatable COM class must have a Public Sub New() 
' with no parameters, otherwise, the class will not be 
' registered in the COM registry and cannot be created 
' via CreateObject.

Obviously though I want to create more subroutines with the new keyword that allow for different parameters. However, when I try to do this and implement the objects in VBA I get an error when trying to input the parameters saying "End of statement expected". If anyone has any information that would greatly be appreciated.

Thank you.

A: 

All classes exposed to COM must have a parameterless constructor - period. The reason is that when the client instantiates a class the call eventually goes into CoCreateInstance() global function (or IClassFactory::CreateInstance() which is almost the same). CoCreateInstance() (or IClassFactory::CreateInstance()) have no means for passing parameters into the constructor of the class so that class must have a paremeterless constructor - that constructor will be used to instantiate the class internally.

If you need more than a paremeterless constructor - use a factory class. Pseudocode:

// this should be made COM-exposed
interface IYourClassInterface {
};

// this should not be made COM-exposed
class CYourClass {
public:
    CYourClass( parameters ) {}
};

class CYourClassFactory {
public:
   CYourClassFactory() {} //<- parameterless constructor
   IYouClassInterface* CreateInstance( parameters here )
   {
      return new CYourClass();
   }
};

this way you have a factory class with a paremeterless constructor. You instantiate the factory and then call its creator method for instantiating your class.

sharptooth