Manish
Manish

Reputation: 1769

About RTTI definition on wikipedia

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?

Upvotes: 2

Views: 253

Answers (1)

The important bit is when they do:

xyz_pointer = dynamic_cast<xyz*>(abc_pointer);

Later on to cast it back to an xyz. Not all abcs will be xyzs, even though all xyzs are abcs. Here the dynamic_cast says "if it is one of these then cast it, otherwise stop and give me NULL instead of doing bad things". dynamic_cast is 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 an xyz* too. Imagine the function:

void (abc *ptr) {
  if (dynamic_cast<xyz*>(ptr)) {
    //...
  }
  else {
    //...
  }
}

In that general instance there's no way to tell if what you're given can be cast to an xyz without looking at its type information at runtime, which is exactly what dynamic_cast does.

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_cast and RTTI should be a last resort when designing C++.

Upvotes: 4

Related Questions