Saturday 28 July, 2007

RTTI

Run Time Type Information (RTTI) is the concept which facilitates us to identify type of a polymorphic object at run time (typeid operator) and to perform type-safe down casting. There is an article already in this blog about type-safe down-casting  - dynamic_cast.

typeid is an operator which can be used to find out the dynamic type of a polymorphic object. It can be used to identify the type of the object referenced by or pointed at run time.

When do we need to use it?

Ideally never. If we design the system properly we shouldn't be using this operator. But in certain cases where we cannot avoid, we may have to use typeid operator.

Let's look at an example.

class CShape
{
    ...
};

class CCircle : public CShape
{
    ...
};

class CRectangle : public CShape
{
    ...
};

void Draw(CShape *pShape)
{
    if(typeid(*pShape) == typeid(CCircle))
    {
        cout<<"Circle"<<endl;
    }
    else if(typeid(*pShape) == typeid(CSquare))
    {
        cout<<"Circle"<<endl;
    }
}

int main()
{
    CCircle *circle = new CCircle();
    CSquare *square = new CSquare();

    Draw(circle);
    Draw(square);
}

This prints "Circle" and "Rectangle".

In function Draw(), typeid is returning the polymorphic type of the object pointed by pShape which is unknown at compilation type.

typeid uses RTTI to find out the class type at run time.

2 comments:

Anonymous said...

For nested class:

#include iostream
#include typeinfo

using namespace std;

class CA
{
class CB{};

CB *m_inner;
public:

CA():m_inner(new CB)
{}

~CA()
{
delete m_inner;
}

CB* get_inner()
{
return m_inner;
}

};

int main()
{

CA obj;
cout << typeid(obj).name() << endl;
cout << typeid(*obj.get_inner()).name() << endl;
}

Anonymous said...

The typeid() also works with non-polymorphic classes, but the behaviour is undefined. The code compiles properly.