fast run-time type idenitification 
Author Message
 fast run-time type idenitification

Hi

I need to determine as quickly as possible if a object is part of a type
hierarchy.

Check out the class hiearchy below.

Class hierarchy

A -----E
|
|
B------C
|
|
D

What would the following be the fastest way to determine this?

D* p;
// initialized somewhere in the program
IsB(p);        // return true;

E* g;
IsB(g);     // return false;

bool IsB(A* p) {

try {
    B* p = dynamic_cast<B*>(p);
    return true;

Quote:
}catch(std::bad_cast &e) {
    return false;
}
}

or would something along the lines with typeid be the fastest.

Thanks
J.



Sun, 02 Nov 2003 12:54:13 GMT  
 fast run-time type idenitification

Quote:

>Hi

>I need to determine as quickly as possible if a object is part of a type
>hierarchy.

>Check out the class hiearchy below.

>Class hierarchy

>A -----E
>|
>|
>B------C
>|
>|
>D

>What would the following be the fastest way to determine this?

>D* p;
>// initialized somewhere in the program
>IsB(p);        // return true;

>E* g;
>IsB(g);     // return false;

>bool IsB(A* p) {

>try {
>    B* p = dynamic_cast<B*>(p);
>    return true;
>}catch(std::bad_cast &e) {
>    return false;
>}
>}

Only the reference form of dynamic_cast can throw an exception, so you
can reduce that to:

bool IsB(A* p)
{
   return dynamic_cast<B*>(p);

Quote:
}

BTW, there's a bug such that a failed reference-type dynamic_cast
throws the bad_cast defined by <typeinfo.h>, not std::bad_cast defined
by <typeinfo>.

Quote:
>or would something along the lines with typeid be the fastest.

That's hard to say, but I would guess dynamic_cast would be faster.
You'll have to profile to be sure.

--
Doug Harrison [VC++ MVP]
Eluent Software, LLC
http://www.eluent.com
Tools for Visual C++ and Windows



Sun, 02 Nov 2003 13:16:25 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Determining type at run-time or compile-time

2. run time type checking

3. Choose type of the object in run-time

4. Bug in C# run-time type information?

5. Q: malloc and type info - fatal run-time eror

6. Data types at run time

7. Determine Column Data Type at run time

8. Run-time type define

9. Run-time type information

10. Enabling Run-Time Type Information: how?

11. Does run-time type info work correctly?

12. Run-Time Type Information (RTTI) among dlls

 

 
Powered by phpBB® Forum Software