"Steven Lien" <st********@yahoo.com> wrote in message
news:bh**********@news.ethome.net.tw...
| As far as i know, there has 2 ways RTTI in C++
| one is dynamic_cast and another is typeid
|
| Since, my book only pointed me that to use "typeid" and "static_cast"
| conjunction will be much more efficient than "dynamic_cast",
| but what the book does not provide any evidence.
|
| So my question can any explain to me why dynmic_cast is slower than
typeid??
|
| And since it's much slower, why not simply throw it away
Slower at what ? They serve very different purposes.
Consider:
#include <typeinfo>
class One { public: virtual ~One(){} };
class Two : public One {};
class Three : public Two {};
void isThisATwo(One* p)
{
// which one of the following values do you want ???
bool same1 = ( 00 != dynamic_cast<Two*>(p) );
bool same2 = ( typeid(*p)==typeid(Two) );
}
int main()
{
Three p;
isThisATwo(&p); // which result do you want?
}
dynamic_cast does a more exhaustive search, to tell you
whether an instance is of a specific type, *OR* any type
derived from it. typeid() cannot provide this information.
Additionally, dynamic_cast can perform casts that are
not accessible to static_cast:
class Base1 { public: virtual ~Base1(){} };
class Base2 { public: virtual ~Base2(){} };
class Derived : public Base1, public Base2 {};
void f(Base1* p1)
{
// can't be done with a static_cast...
Base2* p2 = dynamic_cast<Base2*>(p1);
}
int main()
{
Derived d;
f( &d );
}
Make sure to read other books about C++...
Regards,
--
Ivan Vecerina <>
http://www.post1.com/~ivec
Brainbench MVP for C++ <>
http://www.brainbench.com