×

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

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

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.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.