×

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic cast in C++. Before that, we will learn about typecasting in C++.

What is Type Casting?

Casting is a technique in which we can use one data type in another data type. The operator used in the casting technique is known as the cast operator. The cast operator is a unary operator. The conversion of one data type to another data type is the main aim of the casting.

The syntax for casting one operator into another operator is as follows.

Syntax:

(Cast type) expression;
    or
 Cast type (expression)

Example 1:

#include <iostream>
using namespace std;
int main()
{
        int p, q;
        float r;


        p = 13;
        q = 24;
        r = (float)p * q;


        cout << "The Result Is: " << r;


        return 0;
}

Output:

The Result Is: 312

Explanation

In the above example, first, the variable p is converted to float then multiplied by q, now the result is also floating float then the result is assigned to the variable r. Now, the value of r is 312

Example 2:

#include <iostream>
using namespace std;


int main()
{


        int p = 11, q = 3;
        float r;
        r = p / q;


        cout << "The Result Is:" << r;


        return 0;
}

Output:

The Result Is: 312

Explanation

In the above case, the variable r is 3, not 3.6, because variables p and q both are integer types therefore p/q is also an integer type. After calculating p/q that is int type is assigned to the variable r which is float type. But p/q is int type i.e., 11/3 is 3, not 3.6. Therefore, the value of variable r is 3.

Example 3:

#include <iostream>
using namespace std;


int main()
{


        int p = 11, q = 3;
        float r;


        
        r = (float)p / q;
        cout << "The Result Is :" << r;


        return 0;
}

Output:

The Result Is: 3.66667

Explanation

Now, the variable r is 3.6, because in the above expression first p is converted into float therefore p/q is also float type. 11.0/3 is 3.6. Then that is assigned to the variable r.

C++ supports four types of the casting. These are as follows:

  1. Static cast
  2. Dynamic cast
  3. Const cast
  4. Reinterpret cast

Static Cast:

It is the simple type of cast used in the C++ programming language for casting. It is a compile-time cast. The conversion of int to float and void to pointer is done by static casting. It is also known as the explicit conversion function.

Dynamic Cast:

It is a type of operator that is used to convert data from one type to another type. It can be used for down casting at run time. We need one virtual function at the base class of programming for working on dynamic type casting. It works on a polymorphic base of the programming language.

Syntax:

dynamic_cast <new_type>(Expression)
  1. Downcasting: The casting of a base class reference for the building of class reference is known as downcasting.
  2. Upcasting: The casting of the derived class reference to a base class reference is known as upcasting.

Example 4:

#include <iostream>


using namespace std;
class Base {
        virtual void print()
        {
                cout << "Base" << endl;
        }
};
class Derived1 : public Base {
        void print()
        {
                cout << "Derived1" << endl;
        }
};
class Derived2 : public Base {
        void print()
        {
                cout << "Derived2" << endl;
        }
};
int main()
{
        Derived1 d1;
        Base* bp = dynamic_cast<Base*>(&d1);
        Derived1* dp2 = dynamic_cast<Derived1*>(bp);
        if (dp2 == nullptr)
                cout << "null" << endl;
        else
                cout << "not null" << endl;


        return 0;
}

Output:

not null

Explanation

In this program, there is one base class and two derived classes (Derived1, Derived2), here the base class pointer hold derived class 1 object (d1). At the time of dynamic_casting base class, the pointer held the Derived1 object and assigning it to derived class 1, assigned valid dynamic_casting


Related Topics

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 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.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 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.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.