|
-
April 17th, 2002, 01:21 AM
#1
dynamic cast basics
class Pet{
public:
virtual void eat(){cout<<"Pet eating"<<endl;}
};
class Dog ublic 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?
-
April 17th, 2002, 01:49 AM
#2
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
-
April 17th, 2002, 03:41 AM
#3
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
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|