Finding Information about Classes

July 27, 2014 - C++ / Programação

Some people asked me about the C++ equivalent for the Java’s instanceof reserved word. It is essential to know about some object’s class in runtime, usually relating to some of its ancestors.

For instance, if we have some base class Shape, like the classes Circle, Rectangle e Spiral, how can we find out if some instance from the Shape class is a circle, a rectangle or a spiral, given only a reference to a Shape object?

Differently from Java, C++ supports multiple inheritance, what makes the problem more complex.

In C++, instance identification can be done in a number of ways. The closest to Java is the reserved word typeid and the <type_info.h> header.

typeid parameter can be either an object instance or a class type and it returns a special object for class identification. Such an object supports the == operator for comparing itself to another object of the same type.

The most C++ idiomatic way of identifying an object instance involves forcing a type cast with dynamic_cast<T>. If the conversion is possible, there is some compatible class inside the object’s hierarchy- so we found a member of such a class. Otherwise, a run-time exception is raised, and it must be handled by your code.

› tags: C++ / Java /

Leave a Reply

Your email address will not be published. Required fields are marked *

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