Reputation: 171
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_Rect
s as arguments and then returns a true
or false
. The SDL_Rect
s 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
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
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
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
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