Casting: Up or Down?

C++ Classes provide the convenience of Inheritance to help authors re-use existing code and make applications extensible. The class which does not derive at all is called the Base (or Parent) class and the class which derives from another class is called a Derived (or Child) class. The Inheritance causes an is-a relationship between the base and derived class. Say for example,

class Shape
{
.....
};
class Circle : public Shape
{
.....
};
class Triangle : public Shape
{
.....
};

Classes Circle and Triangle is-a Shape. Now what would happen if we start assigning their objects to each other. Lets find out. It would be wrong to assign a Triangle object to Circle and vice-versa. Though both are derived from Shape class, they both have unique properties which cannot be mix and matched. Now a Circle or Triangle object can be assigned to Shape class. A Circle or Triangle is a Shape, but apart from being a Shape, they have their own unique properties. This process of assigning a derived object to base type is called UpCasting. Since the Shape class doesn’t have the specific properties of Triangle or Circle, the derived object is said to be Sliced. This is referred to as object slicing. If the objects are of pointer type and the member functions are virtual, then appropriate functions are called at run time because to late binding. If the member functions are not virtual, the binding happens are compile time and expected results may not be seen. The opposite of UpCasting is DownCasting. It means, assigning the base class object to a derived type. Now a shape object can draw or resize, but need not necessarily have a radius (ex. Circle) or have three sides (ex. Triangle). We do know that the derived class has a few unique properties and methods not present in the base class. Hence a simple cast of base type to derived type is not possible. Hence such a cast should use the dynamic_cast conversion to achieve this. Dynamic cast evaluates the object being cast to the destination object and determines if it is a safe conversion. It returns an object of resultant type if it is safe or 0 if unsafe.

Reference: http://www.bogotobogo.com/cplusplus/upcasting_downcasting.php

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s