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?


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
    bool check_collision(const SDL_Rect& r);
    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.

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

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.

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.

Need Your Help

What kind of Java member variable is this?

java variables member

I am trying to find out what kind of member variable this is:

getaddrinfo()´╝Ütemporary failure in name resolution

c linux web-crawler

I am writing a web-spider program with C. Now I am given a url's list, and first I need to get the server IP address using function: getaddrinfo, and then ridiculous thing happended:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.