Re: Misuses of RTTI
On 10 ???, 07:13, OuFeRRaT <oufer...@gmail.com> wrote:
"RTTI should only be used sparingly in C++ programs. There are several
reasons for this. Most importantly, other language mechanisms such as
polymorphism and templates are almost always superior to RTTI. As with
everything, there are exceptions, but the usual rule concerning RTTI
is more or less the same as with goto statements. Do not use it as a
shortcut around proper, more robust design. Only use RTTI if you have
a very good reason to do so and only use it if you know what you're
doing." as cited inhttp://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI
I don't understand the sentence:
"but the usual rule concerning RTTI is more or less the same as with
goto statements" can anyone explain it?
The usual rule concerning goto is "don't use it unless you _know_ it's
the most clear way to achieve what you're trying to do here". This
phrase you've cited suggests that the same is applicable to RTTI.
Furthermore, can we talk about the missues of RTTI?
Well, the most typical anti-pattern is using a series of if-else with
typeid in conditionals:
class object {...};
class foo : public object {...};
class bar : public object {...};
....
void do_something(object* obj)
{
if (typeid(*obj) == typeid(foo))
{
foo* foo = static_cast<foo*>(obj);
// do foo-specific processing here
...
}
else if (typeid(*obj) == typeid(bar))
{
bar* bar = static_cast<bar*>(obj);
// do bar-specific processing here
...
}
}
The usual advice in some cases is to use polymorphism - virtual
functions (and, if needed, abstract base classes) instead.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]