# Detecting Overlapping Shapes

I have two classes Circle and Square which derive from an abstract base class Shape.

A Shape*array stores pointers to the Circle and Square objects (which include their random position in a 2D grid).

The objective is to determine which shapes in the array overlap and the objects themselves should contain the methods to calculate this. For example, the Square class would have methods: bool overlapsWithSquare(Shape s) and bool overlapsWithCircle(Shape s).

My idea is to construct two for loops which compare each and every shape in the array, however, how would my program know which method to call upon as we don't know what sub-type each Shape object is?

If the actual type was known, I could have two virtual methods in each object, bool overlaps(...) with different parameters Square s and Circle c.

• Nov 24, 2017 at 6:10

I had solved a similar problem by simplifying my geometry. In my case there was only one such function: bool overlaps(Shape)
• A shape with only 3 values was assumed to be a circle [x, y, radius]
• A shape with only 4 values was assumed to be a line [x1, y1, x2, y2]
• A shape with any even number of values > 4 is a polygon [x1, y1, ... xn, yn]
This article did wonders for me understanding this in case you haven't chosen a method for actually implementing your overlaps function yet: http://www.metanetsoftware.com/technique/tutorialA.html