×

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider the Parent and Child classes, which have two types of objects, parent_objct and child_objct, which can be cast into Parent to Child and Child to Parent using C++ programming's Upcasting and Downcasting.

Casting in C++ :

When transforming one type of objects to another, the phrase "casting" is commonly used in programming. It's essentially a "forced conversion", in which you change one type to another manually.

Example :

float x = 7.68;
int y;
 
y = (int)x;

In the above example, we were able to assign a value to y by casting x into an int, despite the fact that y is an int. The float value of x, 7.68 loses all of its digits that are placed after the decimal point and is transformed to an int.

In C++, we may use pointer references to build a "is a" relationship between the parent and child classes. There are two main kinds of casting that may be done:

  • Upcasting
  • Downcasting

Upcasting in C++ :

Upcasting is the process of creating the pointer or reference of the derived class from the pointer or reference of the base class. When compared to downcasting, upcasting is a safer option. It enables public inheritance, which allows a reference to be automatically cast from one class to the other without the need for an explicit typecast. Upcasting creates an is-a relationship between base and derived classes by default.

Base *pntr = &derived_objct; 

The derived class can inherit all of the base class attributes, including data members and the member function, and use the derived class object to run the function, just like a base object.

When a derived class object is provided by the value as a base class object, upcasting can result in object slicing.

Whenever we send out a message to an object that has a virtual member function, the object will perform the proper thing, even if upcasting is used.

Example :

#include <iostream> // std::cout
using namespace std;


class Base 
{
public:
    void baseFunc() 
    {
        cout<<"Base Function!"<<endl;
    }
};


class Derived: public Base 
{
public:
    void derivedFunc()
    {
        cout<<"Derived Function!"<<endl;
    }
};


int main() 
{ 
    Derived dObjct;


//Upcasting – Here, the implicit upcasting is allowed
    Base *bPntr = &dObjct;


    bPntr -> baseFunc();


    return 0; 
}

Output :

Base Function!

Explanation :

In the above example, we explained the concept of upcasting. We used a public base class with a void function called baseFunc(). Then we created a derived class from the public base class having a function called derivedFunc(). Then we used implicit upcasting, using a base pointer bPntr pointing towards the derived object dObjct and resulting in the calling of baseFunc().

Downcasting in C++ :

Downcasting is the opposite of upcasting. Upcasting is the polar opposite of downcasting. It changes the value of a base class pointer to a derived class pointer. Manual downcasting is a requirement. It implies we’ll have to define a type cast explicitly.

The explanation for this limitation is that in most circumstances, the is-a connection is not symmetric. The class member procedures that utilised such data members would not really be applicable to the base class if a derived class added additional data members. It is not as safe to downcast as it is to upcast. A downcast is only safe if the object being referenced at runtime is indeed a derived class object.

Derived *d_pntr = &b_objct;

Example :

#include <iostream> // std::cout
using namespace std;


class Base 
{
public:
    void baseFunc() 
    {
        cout<<"Base Function!"<<endl;
    }
};


class Derived: public Base 
{
public:
    void derivedFunc()
    {
        cout<<"Derived Function!"<<endl;
    }
};


int main() 
{ 
    Base bObjct;


// explicit type casting is required here
    Derived *dPntr = (Derived *) &bObjct;
    dPntr -> derivedFunc();


    return 0; 
}

Output :

Derived Fun

Explanation :

In the above example, we explained the concept of downcasting. We used a public base class with a void function called baseFunc(). Then we created a derived class from the public base class having a function called derivedFunc(). Then we used explicit type casting, using a derived pointer dPntr pointing towards the base object bObjct and resulting in the calling of derivedFunc().


Related Topics

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.