Self-Registering Objects in C++
A rather old (but nice) article by about self-registering c++ objects. quote from www.drdobbs.com:
An interesting design limitation with C++ is that all the places in the code that create objects have to hardcode the types of objects that can be created because all the usual methods of creating an object in C++, such as
new(classname), require you to specify a concrete type for the class name. This design breaks encapsulation. The situation is understood well by many beginning C++ designers, who try to find a virtual constructor that will create classes without knowing the exact type. These beginners quickly find out that C++ doesn’t have such a thing.
Since the functionality isn’t built into C++, I will add it by creating a class that can create other classes based on some criteria instead of a concrete type. Classes designed to create other classes are frequently called “factories.” I’ll call the class described in this article the “specialty store,” because it only works with objects that are closely related and it leaves the actual work of creation to other classes.
At compile time, the specialty store has no knowledge of the concrete classes it will be working with, but those concrete classes know about the specialty store. There are two remarkable things about this arrangement: A specialty store doesn’t contain a single
newstatement; and the specialty store’s implementation doesn’t include the header files for any of the classes that it will create at run time. (Instead, when the specialty store is asked for a new object, it queries the classes it knows how to create, asking each if it is appropriate for the current situation — if so, then that class is asked to create an instance of itself.)
For the entire article and the source code, follow this link.