Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic down cast to abstract class (C++)

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.

like image 256
tim_a Avatar asked Apr 15 '14 16:04

tim_a


People also ask

Why downcasting is not safe in C++?

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.

What is dynamic cast in C?

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).

What is Upcasting in C?

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.

Is downcasting possible in C#?

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.


2 Answers

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.

like image 119
Neil Kirk Avatar answered Sep 24 '22 10:09

Neil Kirk


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.

like image 35
atoMerz Avatar answered Sep 22 '22 10:09

atoMerz