Please help me. Where to use <dynamic_cast> in c++ with example?
-
behavior of with abase/derived scenario and how it is useful.thanks in advance.
-
behavior of with abase/derived scenario and how it is useful.thanks in advance.
-
behavior of with abase/derived scenario and how it is useful.thanks in advance.
In general I would suggest you don't use it, having to tends to suggest you have some badly designed code. Prefer inheritance and virtual functions.
Steve
-
In general I would suggest you don't use it, having to tends to suggest you have some badly designed code. Prefer inheritance and virtual functions.
Steve
I concur with Stephen. Almost every example I've seen is contrived. There are a few exceptions, though with some of those better design would prevent having to use it.
-
dynamic_cast must be useful in parent child relation of classes. It helps to determine object type in a hierarchy. i.e - class Base{ }; class Derived1:public Base{ void der1Fun(){} }; class Derived2:public Base{ }; int main() { Base *bPtr = new derived1(); //now we want to call a derived1 function let der1Fun() Derived1* dPtr = 0; if( dPtr = dynamic_cast(dPtr) ){ dPtr->der1Fun() } else{ //Display the object is not of derived1 type } return 0; } I think this is why we need dynamic_cast.