I realize this is a very specific question so it would be helpful if the answer people give includes explicit codes on how to do this. Thanks.
I have an abstract base class Shape:
class Shape
{
.....
virtual bool GetIntersection(Shape* _shape) = 0;
}
class Circle : public Shape {...}
class Triangle : public Shape {...}
Both these derived classes overrides GetIntersection;
I have:
//main.cpp
....
Shape* shape;
Shape* circle = new Circle;
if(input == 0) shape = new Circle;
else shape = new Triangle;
circle->GetIntersection(shape);
which gives an error.
I read something about visitor patterns and think that this might be the way to solve my problem as I basically need to determine which derived class the parameter to GetIntersection is using. Can someone explain how I would implement a visitor pattern for this case? Or if there is another simpler solution to this problem.
Any help would be appreciated.
I’m right now facing the same problem with collisions between different shapes.
I think we cannot use the Visitor pattern “as is”, because it requires that the classes of a hierarchy A (visitors) visit the classes of another hierarchy B (visited elements), where the classes of B only know about the abstraction of A (IVisitor, for example) while the classes of B know about the subclasses of A (VisitedElement1, VisitedElement2… subclasses of VisitedElement).
In our case, we are trying to visit Shapes with Shapes while keeping our Shape class decoupled from the subclasses, so the Visitor pattern doesn’t apply.
The best solution I can think of is that the Shape class, directly or through another interface, declares “GetSpecificIntersection” methods for all the subtypes:
Therefore, you must implement those specific intersection methods for each kind of shape to any other kind of shape and the Shape class is coupled to all the possible shapes. If I’m not wrong, this violates OCP but preserves LSP.
Another option I’ve just come up with is to “favor composition over inheritance” and make something like this:
It’s the same as before, but by doing this you decouple your Shape class (which is the interface used by the classes of your game) from the different “Figures” (I didn’t come up with a better name), so adding new Figures shouldn’t even lead to recompile your client classes. This violates OCP only in the “Figures” hierarchy, and preserves LSP for both “Shape” and “Figure”.
If someone can suggest a better way to do this while avoiding downcasting, I’ll be very thankful 😀