Topic: Getting object class at runtime in order to cast


Author: belanger@sgi_dev04.cdst.hydro.qc.ca (Jean-Pierre Belanger)
Date: Thu, 10 Nov 1994 21:41:40 GMT
Raw View
Hi,

In my project, there is a time when a cast to a base class seems
appropriate. Some people are telling me that I should never do this, even
if I know the type of the object involved.

C++ doesn't provide a way to get the class of an object at runtime but I've
been told that the ANSI/ISO C++ committee voted a proposition in order
to include that capability in the language (march 1993).

Could someone tell me the reasons why they wanted to include that
capability ?

Do you have any advice ?

Thanks,
JPI

--
Jean-Pierre Belanger
Hydro-Quebec
5100 Sherbrooke east, 8th floor
Montreal, PQ, Canada H1V 3R9
tel : 514-251-3086 fax: 514-251-3110




Author: b91926@fsgm01.fnal.gov (David Sachs)
Date: 11 Nov 1994 11:21:13 -0600
Raw View
belanger@sgi_dev04.cdst.hydro.qc.ca (Jean-Pierre Belanger) writes:

>Hi,

>In my project, there is a time when a cast to a base class seems
>appropriate. Some people are telling me that I should never do this, even
>if I know the type of the object involved.

>C++ doesn't provide a way to get the class of an object at runtime but I've
>been told that the ANSI/ISO C++ committee voted a proposition in order
>to include that capability in the language (march 1993).

>Could someone tell me the reasons why they wanted to include that
>capability ?

>Do you have any advice ?

Actually, casting from a derived class to a base class has
always been fairly safe. It is the reverse direction, casting from
a pointer or reference to a base class to a pointer or reference to
a derived class that has caused problems.

Several C++ compilers (and their associated class libraries) devised
kludgy system dependent methods to determine and use the actual type
of an object. It did not take long before the standards committee
saw the need for RTTI (Run Time Type Identification), which has
recently (well a year ago) started appearing in commercial compilers.

RTTI functions are only usable with classes that have at least one
virtual function. The "typeid" keyword can be used to determine
the actual type of a pointer or reference.

The form of RTTI, that will probably be the most commonly used, is
the dynamic_cast facility. dynamic_cast can be used to convert a
pointer or reference in a safe-system independent manner. e.g.

If class A has at least one virtual function, class B is derived
from A, and p is a pointer to A, you can convert p to a pointer to
B with the expression:

   ...  dynamic_cast<B*>(p) ...

If p does NOT point to an object of class B (or a subclass of B),
then the result is NULL.