I come from a Java background, where classes which extend (inherit from) other classes are often passed around as the super class. I was hoping to do something similar in C++, but I have never worked with C++ inheritance before. I currently have the following:
class Obstacle{
double get_position(){return position;}
};
class Wall : public Obstacle {
double get_normal(){return normal;}
};
Obstacles, in general, can be any shape, but Walls are rectangular and therefore have an easily designed normal, which would not be appropriate for most Obstacles to have. However, another class has an aggregated std::vector<Obstacle*>
which contains all Obstacles. When iterating through these Obstacles and doing calculations, I need to do separate calculations for separate types of Obstacles (there's a get_type()
function in the superclass as well). When I have a Wall, I'd like to be able to call get_normal()
, but if I try static_cast<Wall>(current_obstacle)->get_normal()
I get the compilation error: no matching function call to Wall(Obstacle*&)
. It also gives the same error if I use ((Wall)current_obstacle)->get_normal()
. It seems as though I should make a Wall
constructor which takes an Obstacle
and creates a new Wall
object, but these doesn't seem to make sense to me.
In Java, I can cast any class to its subclass using ((Wall)current_obstacle).get_normal()
. Is this possible in C++ as well? Do I have to create a constructor? Thanks in advance. Sorry for my lack of understanding.