We know how to use dynamic casting,but why do i need it ? In which situation ,we will feel about this mechanism....
there are 4 type of casting c++ provides,
1) static_casting
2 const_casting
3) dynamic_casting
4) reinterprit_casting
Here i will discuss about only dynamic one,
whatever i do with dynamic_casting , i can achive the same by C Style casting. So why do i need it...? There are some situation , we should go for dynamic casting.
First i would like to discuss what is dynamic casting.
1) Run-time checked casts in an inheritance hierarchy
2) Finding the beginning of an object
3) Meant for downcasting from a base class to a derived class. This check is done at runtime (as opposed to static casting which can generate the necessary code to do the casting at compile time).
4)Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
5)The base class must be a polymorphic one (by declaring virtual)
example1
class B
{
public:
void show()
{
cout<<"I am in Class B \n"; } /*virtual*/ ~B() { } }; class D : public B { public: void dis() { cout<<"i am in derive class Dis\n"; } }; int main() { B *bPtr = new B; D *dPtr = dynamic_cast
// D *dPtr = (D*)(bPtr);
dPtr->show();
}
Here the above programm will show error because source type is not polymorphic
No comments:
Post a Comment