Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bad_cast exception?

26 views
Skip to first unread message

Doug Mika

unread,
Jul 16, 2015, 8:56:14 PM7/16/15
to
Why doesn't the following program throw a bad_cast exception? How can the cast possibly suceed?

#include <iostream>
#include <typeinfo>

using namespace std;

class Mammel{
public:
void Run(){
cout<<"Mammel runs on land"<<endl;
}

virtual ~Mammel(){}
};

class Human:public Mammel{
public:
void Run(){
cout<<"Human runs slow"<<endl;
}
};

class Fish{
public:
void Swim(){
cout<<"Fish swims in water\n";
}

virtual ~Fish(){}

};

class Tuna:public Fish{
public:
void Swim(){
cout<<"Tuna swims really fast\n";
}
};

class Carp:public Fish{
public:
void Swim(){
cout<<"Carp swims really slow\n";
}
};


int main()
{
Human* Charles = new Human();
Carp* carp;

try{
carp = dynamic_cast<Carp*>(Charles);
cout<<"Cast succeeded"<<endl;
}catch(std::bad_cast& exc){
cout<<"Exception: Bad Cast"<<exc.what()<<endl;
}

return 0;
}

Paavo Helde

unread,
Jul 17, 2015, 2:51:11 AM7/17/15
to
Doug Mika <doug...@gmail.com> wrote in
news:e4509378-0984-4446...@googlegroups.com:

> Why doesn't the following program throw a bad_cast exception? How can
> the cast possibly suceed?

It does not succeed - the resulting pointer will be NULL. The bad_cast
exception is thrown only when casting to a reference type. By using
either a pointer or a reference type you decide whether you want an
automatic exception or not.

Doug Mika

unread,
Jul 17, 2015, 11:33:49 AM7/17/15
to
What do you mean by an automatic exception?

Paavo Helde

unread,
Jul 17, 2015, 12:06:25 PM7/17/15
to
Doug Mika <doug...@gmail.com> wrote in
news:25218790-50eb-4272...@googlegroups.com:
>
> What do you mean by an automatic exception?

bad_cast

0 new messages