Alidaco
Alidaco

Reputation: 171

Where is the best location for this function? C++

Is it alright to have a function that is not a part of any specific class when using an object-oriented approach. In my case, I would like to have a check_collision() function that takes two SDL_Rects as arguments and then returns a true or false. The SDL_Rects would be found inside existing objects like a character class or a tile class. Is there a good place to put this function? Am I overlooking a better approach to this problem?

Upvotes: 2

Views: 133

Answers (4)

J. Calleja
J. Calleja

Reputation: 4905

Using a free function is a valid approach. Declare it inside a namespace so you do not populate the global scope. It is better if the function can be declared as not friend of the class.

Upvotes: 0

Chad
Chad

Reputation: 19042

I will post up the only dissenting answer (for now). Since you have an already existing type (SDL_Rect) that you don't own (its included from a 3rd party), I would suggest to implement this as a free function as you have suggested in your original answer. In my opinoin, this will be the cleanest approach for your direct question.

bool check_collision(const SDL_Rect& l, const SDL_Rect& r);

Your other option is to write a class that wraps SDL_Rect and provides collision detection, like this:

class CD_SDL_Rect
{
public:
    bool check_collision(const SDL_Rect& r);
private:
    SDL_Rect r_;
};

But that seems like overkill for this particular case.

If you already had a DisplayableObject class that all displayable objects derived from I may be swayed to suggest adding this as a member, but that doesn't appear to be the case.

Upvotes: 0

Gian
Gian

Reputation: 13955

I would have some kind of "DisplayObject" class from which all of your displayable elements that you might want to check collision on are inherited. Then, place the collision check inside that.

Upvotes: 0

Dan F
Dan F

Reputation: 17732

The approach I would use for object oriented collision detection would be to have the object have a check_collision() function that takes in another of its type, and performs the check that way. you can then use polymorphism and inheritance to define your shape tree and perform all checks through a single function

Upvotes: 1

Related Questions