What is casting in C++? What is a cast operator? What types of casting can be used in C++? What is dynamic_cast in C++? How can I use dynamic_cast in C++?
C++ is a fast and powerful programming language and excels at all sorts of different operations, such as manipulating data, operations with pointers, operations between classes, etc. In C++, both structs and classes can be used with dynamic_cast operations.
In this post, we will explain how to use dynamic_cast in C++.
What is do we mean by ‘cast’ in C++?
Casting is a technique by which one data type to another data type. The operator used for this purpose is known as the cast operator. It is a unary operator which forces one data type to be converted into another data type. It takes on the format:
In C++, a cast operator is an Unary Operator which forces one data type to be converted into another data type.
In general, C++ supports four types of casting:
- Static Cast
- Dynamic Cast
- Const Cast
- Reinterpret Cast
In C++ what is a Dynamic Cast?
A Dynamic Cast (dynamic_cast) is a safe cast operator that converts pointers or references to classes up, down, and sideways along the inheritance hierarchy. This cast is used for handling polymorphism. We can use dynamic_cast when we cast to a derived class. Thus, it can be used exclusively in inheritance when you cast from base class to derived class.
Is there an example of a Dynamic Cast in C++?
This is a simple example of using dynamic cast where the base is TBase.
1 2 3 |
derived = dynamic_cast<TDerived*>( base ); |
Here is the full example of how to perform a Dynamic Cast,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include<iostream> #include <exception> class TBase { public: float base_g = 9.81; virtual void dummy() { }; }; class TDerived: public TBase { public: float local_g = 9.78; }; int main() { TBase * base = new TDerived; TDerived * derived; derived = dynamic_cast<TDerived*>( base ); std::cout << derived->base_g << std::endl; std::cout << derived->local_g << std::endl; getchar(); return 0; } |
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.