C++ – Coding Practice: Class vs. Free Functions

cclass-design

I am currently writing my first bigger project in c++. Its basic linear algebra. I am aware that boost libraries and others exist, but for various reasons I need to write my own. Purpose of the library is to perform certain vector operations (adding, substraction, etc. …) for statistical data analysation. So ease of use of the functions has to be taken into consideration.

I started to write a class:

typedef std::vector<double> vec;
typedef std::vector<std::vector<double> > mat;

class Vector{
public: 
    Vector(){} 
    Vector(vec){}
    ~Vector(){}

    //functions to act on the vectors
    vec add(double){...}
    //many more... 

private:
    vec v
}; 

I soon realised that for simple vector arithmetic the class had some inconveniences: the missing assignment operators came to haunt me rather quickly.

Since I do not have long term coding experiences I want to know whether a "simple" file that contains all the necessary functions like:

 from Vector.h:

 typedef std::vector<double> vec;
 typedef std::vector<std::vector<double> > mat;

 vec add(vec v, double d){...};
 ...

is a proper solution for this kind of problem or if it is preferable to consider the class solution?

Best Answer

When you want to represent distinct concepts, you should create separate types. Yes, this may come with some boilerplate for operator overloading, but having distinct types may offer significant advantages down the line.

std::vector is a generic dynamic array, not a mathematical vector (despite borrowing its name). So yes, you should create a separate type.

Whether the operations you want are then implemented as members or as free functions is a separate design decision. I recommend reading Effective C++.

Related Topic