-
dynamic cast basics
class Pet{
public:
virtual void eat(){cout<<"Pet eating"<<endl;}
};
class Dog:public Pet{
public:
void eat(){cout<<"Dog eating"<<endl;}
virtual void sleep(){cout<<"Dog sleeping"<<endl;}
};
int main()
{
Pet* qq=new Pet;
//Dog* DD=(Dog*)qq;[1]
Dog* DD=dynamic_cast<Dog*>(qq);[2]
DD->eat();[3]
}
In the above the compilations for both static cast and dynamic cast go through.But while static cast executes [3] successfully,dynamic casting causes segmentation fault at [3].How do we explain this?
-
Re: dynamic cast basics
the dynamic casting will return NULL because qq is not a dog. Thus then next statement you are doing on a NULL pointer.
the static casting is dangerous here but you got away with it.
The best things come to those who rate
-
Re: dynamic cast basics
Here you see the reason why dynamic_cast exists. The static cast may well have worked by sheer fluke, but it could have just as easily caused mayhem (and in a larger program probably would have). dynamic_cast, however, returns 0 (NULL) because qq is NOT a Dog (and it's dangerous to pretend that it is) - in other words, it's telling you that you did something illegal. static_cast isn't that kind.
He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf