im curious as to why in the world anyone would ever upcast or even downcast an object in their program?

class shape {
};

class circle : public shape {
};

int main ()
{
circle a;
shape b;

b = (shape)a;



return 0;
}

Let us say we have a base class known as Animal that has a virtual method Eat. We derive some child classes Lion, Bear, Bird. Now we want to have a collection of these creatures and since they all derive from Animal, we can create an Animal array and instantiate as many of the child classes and store them in the array (up casting). We can then iterate through the array and call the Eat method on each animal, an due to the magic of polymorphism, the correct one for each child class will be called.

But, we have another method in Bird called Fly. It's not suitable for the base class because all Animals don't fly so we put it in the Bird class. We need the birds in our array to fly but if you attempt to call Fly on any of them you'll get an exception. So we have to downcast to the Bird class so we can use the methods that are specific to it.

commented: nice +36

To enable polymorphism

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.