0

In a specific program I'm coding, I'm having trouble to decide whether to use function pointer or an Observer-pattern class.

There is a struct called Universe which runs n-body simulations. Occasionally there are some collision between some of its bodies, and I wanted to "listen" to these events. I came up with 2 options:

Declare a function pointer to be called when the simulation end up with a collision:

struct Universe
{
    //... simulation stuff

    //a "user-defined" callback when a collision occurs
    void (*onCollision)(vector<Body*>& collidingList, Body& resultingMerger);
}

Define a CollisionListener class to be derived by registered "listeners" and notify about collision:

struct Universe
{
    //... simulation stuff

    //class to be derived
    struct CollisionListener
    {
        //gets called when a collision occurs
        virtual void onCollision(vector<Body>& collidingList, Body& resultingMerger)=0;
    }

    //list of registered listeners. onCollision() is called on each listener for each collision
    vector<CollisionListener*> listeners;
}

Is the second option an overkill? When the number of bodies is high, there should be a lot of collisions.

Hydren
  • 363
  • 2
  • 11
  • What about creating delegates with `std::function`s? – skypjack Apr 25 '16 at 22:16
  • Nothing wrong being overkill. – maxadorable Apr 25 '16 at 23:00
  • I think it depends on the treatment you want to do when the collisions occur. In your function pointer solution I guess you will call the function pointer once, rather than with the delegates you'll call all of them. Or maybe I missed something? – VincentTellier Apr 25 '16 at 23:02
  • 1
    The first option has potentially less calls because you call it once and user class might add additional checks so it doesn't call all the objects involved. The later is much cleaner and extensible but more calls based on number of listeners. You could have both so the user class may have more options to optimize based on how they use it in the implemention. – Striker Apr 25 '16 at 23:10
  • 1
    Possible duplicate of [Virtual Methods or Function Pointers](http://stackoverflow.com/questions/1955074/virtual-methods-or-function-pointers) – doron Sep 07 '16 at 11:02

0 Answers0