What is downcasting?

Consider the following example:
class B { … };
class D : public B { … };
void f()
{
B* pb = new D; // unclear but ok
B* pb2 = new B;
D* pd = dynamic_cast(pb); // ok: pb actually points to a D

D* pd2 = dynamic_cast(pb2); //error: pb2 points to a B, not a D
// pd2 == NULL

}
This type of conversion is called a “downcast” because it moves a pointer down a class hierarchy, from a given class to a class derived from it.

This entry was posted in C Programming, C++, VC++. Bookmark the permalink.

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> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>