Upcasting and Downcasting in C++ with examples

Upcasting:

First, we will look into the upcasting. Converting the derived class pointer to the base class pointer or converting the derived class reference to the base class reference is called upcasting. It allows public inheritance without the need for an explicit typecast.

A Derived object is-a relationship with the base class. The derived class can get the properties of the base class, nothing but it can inherit the data members and member function of the base class.

This means, anything that we can do to a Base object, we can do to a Derived class object.

Downcasting:

Downcasting is exactly opposite to upcasting the opposite of upcasting. It is a process of converting a base-class pointer or reference to a derived-class pointer or reference.

It should possible with the explicit type conversion. Because a derived class could add new data members, the class member functions that used these data members wouldn’t apply to the base class.

Let us look into the small example which will give us clear picture about the upcasting and down casting

The output of the above program is:

The typeid in C++:

If we want to find the two objects are of the same type, we will have the option of typeid. Using the typeid we will find the type of the object.

In the previous example for Upcasting and Downcasting, MyStudent gets the method Disaply() which is not desirable. So, we need to check if a pointer is pointing to the MyStudent object before we use the method, Disaply ().

Note that we included <typeinfo> in the example. The typeid operator returns a reference to a type_info object, where type_info is a class defined in the typeinfo header file.

Here is a new code showing how to use typeid:

The output of the above program is:

Only a MyStudent uses the Disaply () method.