0

I am creating a collision detection method between objects, however the objects can be different shapes, and therefore the collision detection method must act very differently when considering two circles rather than two rectangles, for example. I am wondering if there would be a way to implement polymorphically this so that I could, with any two arbitrary objects call obj1.collision(obj2), and the correct code would be executed. Is there a way to implement polymorphism in a way similar to this?

Coming from Java, a not very elegant way to do this would be to use instanceof to determine the correct method to call, but I am not aware of this type of functionality in C++.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mertvy
  • 23
  • 3
  • 4
    That's called [double dispatch](https://en.wikipedia.org/wiki/Double_dispatch). A pure OOP pattern to implement it is via the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern). [`std::variant::visit`](https://en.cppreference.com/w/cpp/utility/variant/visit) might be of interest – Homer512 Jul 31 '23 at 07:07
  • 1
    Perhaps one of [these questions](/search?q=%5Bdouble-dispatch%5D+%5Bc%2B%2B%5D+is%3Aq) provides your answer? – Toby Speight Jul 31 '23 at 07:10
  • https://gieseanw.wordpress.com/2018/12/29/stop-reimplementing-the-virtual-table-and-start-using-double-dispatch/ – HolyBlackCat Jul 31 '23 at 07:10
  • 2
    `dynamic_cast` is a C++ analogue of `istanceOf`. There are implementations of double dispatch/visitor that rely on it, with their own set of advantages and disadvantages (google "acyclic visitor"). Whatever you do isn't going to be elegant. It's just the nature of the beast. – n. m. could be an AI Jul 31 '23 at 07:38

0 Answers0