capypad
0 day streak
cpp / intermediate
Snippet

Operator Overloading

Operator overloading lets you redefine how standard operators like + or - behave when used with your custom classes.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
class Vector2D {
public:
float x, y;
Vector2D operator+(const Vector2D& other) const {
return {x + other.x, y + other.y};
}
};
 
Vector2D v3 = v1 + v2;
Breakdown
1
Vector2D operator+(...) const
Defines the behavior of the addition operator for the Vector2D class.
2
return {x + other.x, y + other.y};
Creates and returns a new Vector2D object with the summed coordinates.