Your example is a bit of reflection magic that Java can do because it knows everything about the named class at runtime.Originally Posted by drkbkr
C++ is a bit stupider in that regard - so the short answer is, no, there is nothing built into the language that will do what you want. You'll have to code something like that, yourself. The factory class suggestion is a common approach for this kind of thing.
Remember in C++ you are entirely responsible for memory management and class instantiation/destruction. Furthermore, knowledge stops at the base-class/derived-class boundary. To create a derived class, something at some point has to know all the details (header include) of that derived class and either call a 'new' on it, or return a reference to an already-created instance.
That said, there are a lot of tricks and design patterns to do that. I'd start with the factory pattern.
rickb
Bookmarks