Sunday, March 10, 2013

This time we will explore the technique used to determine the type of objects at runtime using Run Time Type Identification(RTTI) in C++.

Basically there are two common ways to achieve this:
1. Use a virtual function in base class and override that method in derived class:

output:

And when you use base class pointer or reference to hold object you may use bptr->typeOf() to detemine the type of object at run time.

2. Another approach which is built into language library is to use typeid() method. This method returns const object of typeinfo type.
For example,

We can also use Explicit Typecasting in C++ using :

dynamic_cast:

It is used to ensure that the object returned after cast is complete object of requested type. If its not so it returns bad_cast exception in case of references and returns null pointer in case of pointers.

Consider non-polymorphic base class and its derived class:

This will not even clear the compilation phase. It will give this error:

Lets convert base class to polymorphic by adding virtual keyword for hello method in base class and check again. This time it clears compilation and the type is checked at run time. This is purely based on RTTI support by compiler.

static_cast:

In this cast operator it is not checked that object returned after casting is actually a type of requested object. It is not type safe. Thus it is upto developers to take care when dereferencing. This works for:

Implicit conversions

Narrowing conversions

Conversions from void *

base class pointer to derived class pointer

derived class pointer to base class pointer

For example:

This will yield:

const_cast:

This cast is useful to convert const to non-const objects. This is used as another alternative to change const objects in a class without using mutable keyword.

For example,

output:

reinterpret_cast:

This cast is used to convert any pointer type to any other pointer type, even for unrelated classes. It can also be used to convert int to pointer and other way round.

For example,

This will yield:

I hope this helps you understand basic typecasting mechanism present in C++. Stay tuned for more fun !