Hi,
I got some understanding about dynamic_cast but could anyone provide me any pratcial scenario where we need dynamic_cast and we do not have other alternative except dynamic_cast
I don't think there is a scenario where we MUST use dynamic_cast, it just gives us the ability to check the validity of the cast, whereas using static_cast we can't know for certain whether it will succeed or not.
class Base
{
public:
virtual ~Base();
};
class Derived1 : public Base
{
char c;
public:
virtual ~Derived1();
};
class Derived2 : public Base
{
long l;
public:
virtual ~Derived2();
};
You can always do this:
1 2
Derrived1* d1 = new Derived1;
Base* b = d1; // upcast is ok because Derived1 is a Base.
But you can't do this.
1 2 3 4
Derrived1* d1 = new Derived1;
Base* b = d1; // upcast is ok because Derived1 is a Base.
Derived1* x1 = b; // downcast is unsafe and fails.
Derived2* x2 = b; // downcast is unsafe and fails.
You can force it, but it's unsafe:
1 2 3 4
Derrived1* d1 = new Derived1;
Base* b = d1; // upcast is ok because Derived1 is a Base.
Derived1* x1 = static_cast<Derived1*>(b); // downcast is unsafe, but happens to be ok
Derived2* x2 = static_cast<Derived1*>(b); // downcast is unsafe and is in fact incorrect
You can do a cast safely with dynamic cast because it uses RuntTime Type Info (RTTI) to determine if the cast is valid.
1 2 3 4
Derrived1* d1 = new Derived1;
Base* b = d1; // upcast is ok because Derived1 is a Base.
Derived1* x1 = dynamic_cast<Derived1*>(b); // x1 is d1
Derived2* x2 = dynamic_cast<Derived1*>(b); // x2 is null
I can't think of a credible example, but suppose you have a function that draws shapes on a device, but there's some optimised method for printing squares...