This section will discuss Upcasting and Downcasting with an example in the C++ programming language. When we convert one data type into another type, the process is called typecasting. But the, Upcasting and downcasting are the types of object typecasting. Suppose the Parent and Child class has two types of object, parent_obj and child_obj, which can be cast into the Parent to Child and Child to Parent using the Upcasting and Downcasting in C++ programming.

Upcasting
It is the process to create the derived class's pointer or reference from the base class's pointer or reference, and the process is called Upcasting. It means the upcasting used to convert the reference or pointer of the derived class to a base class. Upcasting is safe casting as compare to downcasting. It allows the public inheritance that implicitly cast the reference from one class to another without an explicit typecast. By default, the upcasting create is-a relationship between the base and derived classes.
The derived class can inherit all the base class properties that include data members and the member function to execute the function using the derived class object, as we do with a base object.
Program to demonstrate the Upcasting in C++
Let's consider an example to convert the derived class's pointer to the base class's pointer in the C++ programming language.
Program1.cpp
Output
It is the Super function of the Base class
Downcasting
The Downcasting is an opposite process to the upcasting, which converts the base class's pointer or reference to the derived class's pointer or reference. It manually cast the base class's object to the derived class's object, so we must specify the explicit typecast. The downcasting does not follow the is- a relation in most of the cases. It is not safe as upcasting. Furthermore, the derived class can add new functionality such as; new data members and class member's functions that use these data members. Still, these functionalities could not apply to the base class.
Program to demonstrate the downcasting in C++
Let's create an example to downcast the base class's object to the derived class in the C++ programming language.
Program2.cpp
Output
It is the function of the Child class
Program to demonstrate the upcasting and the downcasting in C++
Let's consider an example to use the downcasting and the upcasting in C++ to convert the base class to derive and the derived class's object to the base class.
Program3.cpp
Output
I am in the Parent class
I am in the Parent class
I am in the Myson class
You may be interested in:
>> Is a Chromebook worth replacing a Windows laptop?
>> Find out in detail the outstanding features of Google Pixel 4a
>> Top 7 best earbuds you should not miss
Related Posts:
>> Recognizing 12 Basic Body Shapes To Choose Better Clothes
>>Ranking the 10 most used smart technology devices
>> Top 5+ Best E-readers: Compact & Convenient Pen
0 Comments:
Post a Comment