Re: Casting to a derived class
On Jul 1, 9:17 pm, George Neuner <gneun...@comcast.net> wrote:
The proper way to do downcasting is to turn on RTTI and use
dynamic_cast<>(). dynamic_cast<>() verifies that the actual runtime
object really is of the specified class. If called with a pointer
specification, it will return a new, class specific, pointer to the
object if successful or NULL if the object is not of the specified
type.
The way you use dynamic_cast<>() for safe pointer downcasting is
something like the following:
void main(int argc, char *argv[])
{
base *pb = new der();
der *pd = dynamic_cast<der*>(pb);
if ( pd )
pd->d = 123;
else
// pd == null. cast failed - object not a 'der'
:
}
One important detail - the dynamic_cast can only work with
polymorphic types, otherwise you'll get a compile-time error.
The OP specified classes without virtual functions, so he
won't be able to use dynamic_cast. Only static_cast.
Andy.
P.S. BTW, Hi George!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]