The concept is pretty simple if you have some intuitive understanding of types.
A type is a definition. It defines a "type of thing". For example,
int
is a type that describes integers. Sure enough, part of C++'s definition says that we can add two
int
s together and get another
int
. This shouldn't be too surprising.
The interesting bit is that the words
class
and
struct
allow you to define your own types. For example, if you need to do math on two-dimensional vectors, it could be convenient to define them, by creating a new type named
vec2
. That type definition describes exactly what a vec2 is.
1 2 3
|
struct vec2 { // says: "every vec2 has an x and y position"
float x, y;
};
|
Maybe you need to compute their length, so you create a function to do that:
|
float len(vec2 v) { return std::sqrt(v.x * v.x + v.y * v.y); }
|
Which is how you say that
len(v)
is the length of
v (where
v is some
vec2.)
Maybe you want to be able to add two vec2s together. We could create a function like this:
|
vec2 add(vec2 v1, vec2 v2) { return vec2{v1.x + v2.x, v1.y + v2.y }; }
|
Which is how you say that
add(v1, v2)
is the sum of
v1 and
v2 (where
v1,
v2 both have type
vec2).
Unfortunately, we'd much rather be able to write v1 + v2 and mean the same thing. We can:
1 2
|
vec2& operator+=(vec2& l, vec2 r) { l.x += r.x, l.y += r.y; return l; }
vec2 operator+(vec2 l, vec2 r) { return l += r; }
|
Which is how you say that
v1 + v2
is the sum of
v1 and
v2 (where
v1,
v2 both have type
vec2).