On Tue, 15 Mar 2005 18:28:10 -0800,
go***********@gmail.com wrote:
I think it is quite useful in Polymorphism. For example, Class A has
two subclasses B and C.You have another function with return type as
class A, but the return value maybe an object of class B or class C. So
you have to determine at the run time the return value is actually of
class B or class C . Besides RTTI, how can you achieve this?
Other than class loading based on name, I really don't believe it is all
that useful. One thing you could do is use the type_info's == or !=
operators to check against known types in order to choose an algorithm. No
need for the class's name.
Or you can use compile-time polymorphism. Assuming
your going to use the type to dynamically choose an algorithm, you could
use templates & template specialization. You'd might
provide a generic behavior for all type other than B or C (in your
example) and specialize on B and/or C.
Conversely, if you want ONLY B & C to be handled you can provide a declaration
w/o an implementation for the most generic case and provide an implementation
for the specializations of B & C. This way you would get a compile-time error
if you attempted to choose your algorithm for any case other B & C.
I haven't even touched on using reinterpret_cast, dynamic_cast and their
like. I think if you dig a little deeper, you'll find whatever your
designing will be a lot better off (certainly nowhere near as brittle)
than if you base your design on a bunch of hard-coded static strings.
Consider, for example, what happens when you further subclass B or C? A
B_derived class is still a B, but will not, certainly, return "B" when you
call name(). I think you can see where this leads. I'll leave you to it.