In my program I have a base class (ship
) and four derived classes (pirate
, mercantile
, repairing
, exploring
) and in a member function of repairing
I want to know if an object pointed by a ship *
is of type pirate
in order to be able to handle that case.
So in that member function I have the following if
:
ship * shp;
shp = map[i][j]->getShip(); //random initialization of shp
if( (dynamic_cast<pirate *>(shp)) == NULL) // <- program doesn't enter here
{ . . . } // while it should
But during the runtime I noticed that sometimes the program didn't entered the if
even when shp
was pointing to a non-pirate
object (e.g. exploring
) .
So I tried to see the result of that boolean
value inside the if
by writing the following code:
pirate *prt;
bool test;
if(map[i][j]->getShip()!=0){
prt = dynamic_cast<pirate *>(shp); // <- program crashes here
test = ( prt == NULL );
cout<<test<<endl;
}
But after compiling and trying to run this, the program crashes just at the time dynamic_cast
is used.
So, probably dynamic_cast
isn't working correctly and this is the reason it is not entering the if
in the previous code.
Note that I have used the same method with dynamic_cast
in the rest of my programm to find out the type of an object and it worked properly.
Why is this happening?
Thanks in advance.