I am trying to learn some object orientated programming aspect I know from java in C++. However I am having some difficulties in using dynamic_cast
where I would use instanceof
in Java.
I have a base class Cell
and a derived (abstract) class Obstacle
. I have defined it like this: Obstacle : public Cell
and Obstacle
contains a pure virtual destructor. Now in the Cell
class I want to implement a method bool Cell::isAccesible()
. I've implemented this as follows:
bool Cell::isAccessible() {
Obstacle *obs = dynamic_cast<Obstacle*>(this);
if (obs != NULL) return false;
return true;
}
However I get the following error back:
"the operand of a runtime dynamic_cast must have a polymorphic class type".
What's wrong with the way I want to implement this? Any guidance is appreciated.
Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.
A cast is an operator that forces one data type to be converted into another data type. In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference).
It is the process to create the derived class's pointer or reference from the base class's pointer or reference, and the process is called Upcasting. It means the upcasting used to convert the reference or pointer of the derived class to a base class.
Upcasting is legal in C# as the process there is to convert an object of a derived class type into an object of its base class type. In spite of the general illegality of downcasting you may find that when working with generics it is sometimes handy to do it anyway.
Cell class must have at least one virtual function to use dynamic_cast. Also, if Cell is your base class, it should have a virtual destructor.
You should make isAccessible a virtual function and override it in Obstacle to return false.
What you're doing is wrong. Generally you shouldn't need to cast to a sub type of a class in its base class. If you need it, it is likely a design error. In your case the code should look like this.
virtual bool Cell:: isAccessible()
{
return true;
}
bool Obstacle::isAccessible()
{
return false;
}
P.S. The cause of your error is that Cell
class does not have a virtual method and thus it does not show polymorphic behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With