dynamic_cast causing run time error
Please look at the following code:
Code:
#include <iostream>
using namespace std;
class Pet
{
public:
virtual void speak()
{
cout<<"Pet speak: "<<endl;
}
virtual ~Pet(){}
};
class Dog : public Pet
{
public:
void speak()
{
Pet::speak();
cout<<"AV AV"<<endl;
}
virtual void show()
{
cout<<"This one is new!"<<endl;
}
virtual ~Dog(){}
};
int main()
{
Pet *p=new Dog;
Pet *pb=new Pet;
Dog *dg;
dg=dynamic_cast<Dog*>( p);
if(!dg)
{
cout<<"Zero!"<<endl;
return 1;
}
dg->show();
}
I'm using Visual Studio .net
and when compiling get this warning:
warning C4541: 'dynamic_cast' used on polymorphic type 'Pet' with /GR-; unpredictable behavior may result
and when I execute program crashes.
I don't know why this happens and where could be mistake in this code.