A cast is an operator that forces one data type to be converted into another data type. In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).
Dynamic casting checks consistency at runtime; hence, it is slower than static cast.
Take a look at the function signature of the dynamic cast below:
To use
dynamic_cast<new_type>(ptr)
the base class should contain at least one virtual function.
In the example below, Shape
is the parent class, and it has two derived classes: Square
and Rectangle
. The method dynamic_cast<Square*>(quad)
successfully casts the base class pointer to the derived class pointer. However, since casting a derived class pointer to a base class pointer, and then casting this base class pointer into some other derived class pointer is invalid, dynamic_cast<Square*>(quad1)
returns a NULL
pointer.
#include <iostream>#include <string>using namespace std;// The parent classclass Shape{string s_name;public:Shape(string name): s_name(name){}virtual void get_info(){cout<<s_name<<endl;}};// The child classclass Square : public Shape{int side;public:Square(string S_name, int value): Shape(S_name), side(value){}void get_info(){cout<<"Area of the square is: "<<side * side<<endl;}};// The child classclass Rectangle : public Shape{int length;int width;public:Rectangle(string S_name, int len, int wid): Shape(S_name), length(len), width(wid){}void get_info(){cout<<"Area of the rectangle is: "<<length * width<<endl;}};Shape* create_square(string S_name, int value){return new Square(S_name, value);}Rectangle* create_rectangle(string S_name, int len, int wid){return new Rectangle(S_name, len, wid);}int main() {// quad is the pointer to the parent// class, it needs to be casted to be used to// access the method of the child class.Shape *quad = create_square("Quadliteral", 4);// Trying to downcast the parent class pointer to// the child class pointer.Square* sq = dynamic_cast<Square*>(quad);// dynamic_cast returns returns null if the type// to be casted into is a pointer and the cast// is unsuccessful.if(sq){sq -> get_info();}Rectangle *rect = create_rectangle("Quadliteral", 4, 5);// An example of a valid upcastingShape* quad1 = dynamic_cast<Shape*>(rect);// An example of invalid downcastingSquare* sq1 = dynamic_cast<Square*>(quad1);if(sq1 == NULL){cout<<"Invalid casting."<<endl;}}
Free Resources