dynamic_cast, Recipe 8.7

1 view
Skip to first unread message

OliverG

unread,
Feb 25, 2007, 2:44:16 AM2/25/07
to cpp-cookbook
Maybe others have pointed it out already, but Recipe 8.7 seems
confused and largely incorrect.

Correct explanation:

// Given..
class Derived : public Base { ... };

// Function which uses p polymorphically
void f(Base* p)
{
// Mainly we will want to use the object p points to
// through virtual functions of Base. However if, in the
// event that p points to a Derived, we want to use
// member functions of Derived (which are not overrides
// of Base functions) we have to use dynamic_cast.

Derived* dp = dynamic_cast<Derived*>(p);
// dp will be non-null only if p points to an object of class
Derived.

if (dp)
{
// Can access full Derived interface through dp here.
}
}

Cheers,
Oliver

Ryan Stephens

unread,
Feb 26, 2007, 5:10:07 PM2/26/07
to cpp-co...@googlegroups.com
Hi Oliver,

Thanks for the feedback.  I'll take a look and get back to you in the next day or two.

-Ryan
Reply all
Reply to author
Forward
0 new messages