I was going through the example of RTTI here on wikipedia.
I am confused about this part
abc *abc_pointer = new xyz();
If abc_pointer is being made to point to a xyz object wouldnt it be obvious that that it will get identified.I mean what is the use of comparing
xyz_pointer != NULL
later on and RTTI in general then? Am I missing something here?
The important bit is when they do:
Later on to cast it back to an
xyz. Not allabcs will bexyzs, even though allxyzs areabcs. Here thedynamic_castsays “if it is one of these then cast it, otherwise stop and give meNULLinstead of doing bad things”.dynamic_castis using RTTI for you.In the toy example you can clearly tell (and the compiler could even figure it out if it wanted to) that the
abc*was anxyz*too. Imagine the function:In that general instance there’s no way to tell if what you’re given can be cast to an
xyzwithout looking at its type information at runtime, which is exactly whatdynamic_castdoes.Note that had you used
static_cast<xyz*>(ptr)the cast would always look to have worked, even in cases where it’s not actually legal to do so and most likely lead to undefined behaviour.It should be noted here though that if you find yourself writing lots of
if (dynamic_cast<...that might indicate a “code smell” – you should consider refactoring, probably a virtual method would be more appropriate.dynamic_castand RTTI should be a last resort when designing C++.