Jun 112012
 

What is dynamic_cast in C++. Where is it used?

Solution:

In C++ we can have inheritance hierarchy (one class inheriting from another). For example:

class Person
{
….
};

class Employee : public Person
{
….
};

Employee is a child (or base) class of Person. If you have studied even the basic inheritance, then you must be knowing that the relation between Employee & Person class is “IS-A”. i.e Employee IS-A Person. Hence the pointer of Person class can be assigned an object of Employee class.

Person *ptr = new Employee;

This is used in virtual function calling also, but that’s not our topic today.

If I want to down-cast the pointer (or reference), i.e want to cast the pointer of Person class to Pointer of Employee class, I need to explicitly cast it (even when the pointer to Person class holds the object of Employee class)

dynamic_cast, is used to perform safe casts down or across an inheritance hierarchy. That is, you use dynamic_cast to cast pointers or references to base class objects into pointers or references to derived or sibling base class objects in such a way that you can determine whether the casts succeeded or failed.

Employee * eptr = dynamic_cast<Employee*> (ptr)

Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references).

If you want to perform a cast which does not involve inheritance hierarchy, like casting away const-ness or casting double to int, then you cannot use dynamic_cast. There are other casts in C++ like static_cast, const_cast, reinterpret_cast for specialized purposes.

Please let me know your comments/feedback/suggestion.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)