Vision
Vision

Reputation: 110

When using a header only in C/C++?

is it usual to use for a class like "vec3" only a header?

This is my actual code:

#ifndef VECTOR3_H
#define VECTOR3_H

#include <math.h>

class vec3
{
public:
    double x, y, z;
    vec3();
    vec3(double x, double y, double z) : x(x), y(y), z(z) {}
    double lenght()
    { return sqrt(pow(x, 2) * pow(y, 2) * pow(z, 2));}
    double lenghtSquared()
    { return pow(x, 2) + pow(y, 2) + pow(z, 2);}
    double distance(vec3 v)
    { return sqrt(pow(x - v.x, 2) * pow(y - v.y, 2) * pow(z - v.z, 2));}
    double distanceSquared(vec3 v)
    { return pow(x - v.x, 2) + pow(y - v.y, 2) + pow(z - v.z, 2);}
    float angle(vec3 v)
    { return (float) acos(dot(v) / lenght() * v.lenght());}
    double dot(vec3 v)
    { return x * v.x + y * v.y + z * v.z;}
    void cross(vec3 v) {
        double a = y * v.z - v.y * z; double b = z * v.x - v.z * x;
        double c = x * v.y - v.x * y; x = a; y = b; z = c;}
    void normalize()
    { x, y, z /= lenght();}
};

#endif // VECTOR3_H

Can I better create also a source file instead of only a header? If you have some tips, I like them :)

Thanks in advance

EDIT: And what means inline exactly?

Upvotes: 8

Views: 8875

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254691

The class definition needs to go in a header, if you want it to be generally usable. If it's in a source file, then it's only available within that source file, not in others.

The member function definitions can either be inline like yours are; or you could move them to a source file, leaving just declarations in the class.

There are pros and cons to both approaches. A header-only implementation is easier to share and distribute, and offers more optimisation opportunities since the functions are easier to inline; but can lead to longer build times if there are a lot of large functions included in many translation unit, and makes the header more cluttered if you want to use it as "documentation" for the class interface.

And what means inline exactly?

It means a function is either defined inside a class, or declared inline. In either case, its purpose is to relax the "One Definition Rule", so that you are allowed to define the function in more than one translation unit; and it must be defined in every unit in which it's used. This is necessary if you want the definition to appear in a header (which may be included from multiple units). It gives the compiler a better opportunity to inline function calls, replacing them with the body of the function to avoid the cost of the calls.

Upvotes: 10

RichieHindle
RichieHindle

Reputation: 281765

There's nothing unusual about that, no. In some cases (eg. templates) it's actually required.

In practice, putting the member definitions in a cpp file can make the code easier to manage, and can make building your project faster, but in this case there's so little code that it won't make any difference.

Upvotes: 2

Related Questions