Click to See Complete Forum and Search --> : dynamic cast basics


ranadhir27
April 17th, 2002, 01:21 AM
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?

NMTop40
April 17th, 2002, 01:49 AM
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

Graham
April 17th, 2002, 03:41 AM
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