Run Time Class Handler: Instantiating Classes by Name
Posted
by Ernst Versteeg
on December 18th, 1999
With this class I was able to simply add a file with a new class to my project and to instantiate new objects from this class simply by altering or adding the name of the class in the database or in configuration files. This way I didn't need to add code for the support of the added class to existing code or to register the class with class factories.
So this is VERY useful if you like to disconnect classes from each other on compile level or to avoid making special class factories.
This class is tested and is in use for both 16/32 bit versions.
Notes:
- Use DECLARE_SERIAL and the IMPLEMENT_SERIAL macro for classes
which should be used for this function.
- As with all classes which use DECLARE_SERIAL a default empty constructor
is needed. If you need initialization, a "Create" function be made
and used after a cast of the returned object to the appropriate class.
- DECLARE_DYNCREATE does not work with the 32 bit part of this code, perhaps
somebody knows why.
- As far as I know, this way of coding is part of SmallTalk.

Comments
Solution to make it work with classes in MFC extension DLLs
Posted by Legacy on 06/03/1999 12:00amOriginally posted by: Peter Luxem
ReplyReason DECLARE_SERIAL is needed
Posted by Legacy on 06/02/1999 12:00amOriginally posted by: ChrisD
The list you are travering to find the class name is only created for objects that have DECLARE/IMPLEMENT _SERIAL defined. The IMPLEMENT_SERIAL definition has a line that reads
static const AFX_CLASSINIT _init_##class_name(RUNTIME_CLASS(class_name));
this line instantiates a static AFX_CLASSINIT object for the class suppllied which add it to the list of RuntimeClass names.
Unless you are supllying strings at runtime you can use in your code
ReplyCOBject* pBoj = RUNTIME_CLASS(CreatableClass)->CreateObject();
Chris