C++ Functions – Where to Put Functions Not Related to a Class

cclassfunctions

I am working on a C++ project where I have a bunch of math functions that I initially wrote to use as part of a class. As I've been writing more code, though, I've realized I need these math functions everywhere.

Where is the best place to put them? Let's say I have this:

class A{
    public:
        int math_function1(int);
        ...
}

And when I write another class, I can't (or at leat I don't know how to) use that math_function1 in that other class. Plus, I've realized some of this functions are not truly related to class A. They seemed to be at the beginning, but now I can see how they're just math functions.

What is good practice in this situation? Right now I've been copy-pasting them into the new classes, which I'm sure is the worst practice.

Best Answer

C++ can have non-method functions just fine, if they do not belong to a class don't put them in a class, just put them at global or other namespace scope

namespace special_math_functions //optional
{
    int math_function1(int arg)
    {
         //definition 
    }
}
Related Topic