[Qt-interest] QHash<QString,class>?
Bachrach, Robert L
rob.bachrach at tycoelectronics.com
Mon Jan 12 19:21:49 CET 2009
True, this is more of a C++ question than Qt.
You are essentially referring to a variant of a factory method. I have seen this type of thing implemented in 2 ways:
1 - Create a pure virtual function in your base class, NewWindow, that returns a pointer to a base class object. Each derived class overrides this function, returning a pointer to a new object of its own type. Then, your hash would contain an instance of each derived class. It simply calls the NewWindow function on the element in the hash. Of course, each base class would have to be "registered" by having an instance placed in the hash. Registration could occur in the constructor, since you always create one. Don't forget to delete the objects when you clear the hash.
2 - Probably easier to manage is to create a static member function of each derived class "NewWindow". This static member function acts as the virtual function above. The hash simply stores a pointer to each function. This requires less memory and less memory cleanup, but lacks the compiler error if you forget to declare the function in a derived class. It still requires registration.
Although manual registration is fine, automatic registration can be performed by instantiating a light weight object as a static class variable. The object's constructor could perform the registration.
Please consider using C++ newsgroups for similar questions in the future.
Rob
More information about the Qt-interest-old
mailing list