Lesson 4 of 5
Mini Project Part 6 - Vector2D with Full Operator Overloading
Build a production-quality 2D vector math library with: all arithmetic operators, comparison, stream I/O, subscript, conversion-to-bool, normalise/dot/cross/angle functions, and a Polygon class that uses `std::vector<Vec2>` with overloaded `<<` for printing.
Vec2 Math Library - Complete Operator Overloading
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
#include <sstream>
#include <iomanip>
class Vec2 {
public:
double x, y;
Vec2(double x = 0, double y = 0) : x(x), y(y) {}
// Compound assignment
Vec2& operator+=(const Vec2& o) { x+=o.x; y+=o.y; return *this; }
Vec2& operator-=(const Vec2& o) { x-=o.x; y-=o.y; return *this; }
Vec2& operator*=(double s) { x*=s; y*=s; return *this; }
Vec2& operator/=(double s) { x/=s; y/=s; return *this; }
// Unary
Vec2 operator-() const { return {-x, -y}; }
explicit operator bool() const { return length() > 1e-9; }
// Subscript
double& operator[](int i) { return i==0 ? x : y; }
const double& operator[](int i) const { return i==0 ? x : y; }
// Math
double length() const { return std::sqrt(x*x + y*y); }
double lengthSq() const { return x*x + y*y; }
Vec2 normalised() const {
double l = length();
if (l < 1e-9) throw std::domain_error("Cannot normalise zero vector");
return {x/l, y/l};
}
// Geometric
double angleTo(const Vec2& o) const {
return std::atan2(cross(o), dot(o)); // signed angle
}
double dot (const Vec2& o) const { return x*o.x + y*o.y; }
double cross(const Vec2& o) const { return x*o.y - y*o.x; }
Vec2 rotated(double radians) const {
double c = std::cos(radians), s = std::sin(radians);
return {x*c - y*s, x*s + y*c};
}
Vec2 projected_onto(const Vec2& onto) const {
double d = onto.dot(onto);
if (d < 1e-9) return {};
return onto * (dot(onto) / d);
}
};
// Binary non-member (symmetric)
inline Vec2 operator+(Vec2 a, const Vec2& b) { return a+=b; }
inline Vec2 operator-(Vec2 a, const Vec2& b) { return a-=b; }
inline Vec2 operator*(Vec2 v, double s) { return v*=s; }
inline Vec2 operator*(double s, Vec2 v) { return v*=s; }
inline Vec2 operator/(Vec2 v, double s) { return v/=s; }
inline bool operator==(const Vec2& a, const Vec2& b) {
return std::abs(a.x-b.x)<1e-9 && std::abs(a.y-b.y)<1e-9;
}
inline bool operator!=(const Vec2& a, const Vec2& b) { return !(a==b); }
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << std::fixed << std::setprecision(3) << "(" << v.x << ", " << v.y << ")";
}
// Polygon using Vec2
class Polygon {
std::vector<Vec2> vertices_;
public:
explicit Polygon(std::vector<Vec2> verts)
: vertices_(std::move(verts)) {}
double area() const { // Shoelace formula
double a = 0;
size_t n = vertices_.size();
for (size_t i = 0; i < n; ++i) {
const Vec2& p = vertices_[i];
const Vec2& q = vertices_[(i+1)%n];
a += p.x * q.y - q.x * p.y;
}
return std::abs(a) / 2.0;
}
Vec2 centroid() const {
Vec2 c;
for (const auto& v : vertices_) c += v;
return c / (double)vertices_.size();
}
friend std::ostream& operator<<(std::ostream& os, const Polygon& p) {
os << "Polygon{";
for (size_t i = 0; i < p.vertices_.size(); ++i) {
if (i) os << ", ";
os << p.vertices_[i];
}
return os << "}";
}
};
int main() {
Vec2 a{3.0, 4.0}, b{1.0, 2.0};
std::cout << "a=" << a << " b=" << b << "
";
std::cout << "a+b=" << (a+b) << "
";
std::cout << "|a|=" << a.length() << "
"; // 5.0
std::cout << "a·b=" << a.dot(b) << "
"; // 11
std::cout << "â=" << a.normalised() << "
"; // (0.6, 0.8)
std::cout << "a rotated 90°="
<< a.rotated(3.14159/2) << "
"; // ~(-4, 3)
Vec2 proj = a.projected_onto(b);
std::cout << "a projected onto b: " << proj << "
";
Polygon triangle{{
{0,0}, {4,0}, {0,3}
}};
std::cout << triangle << "
";
std::cout << "Area: " << triangle.area() << "
"; // 6.0
std::cout << "Centroid: " << triangle.centroid() << "
";
return 0;
}Common Mistakes
- Floating-point equality with `==` - `a.x == b.x` fails for computed values due to rounding. Always compare floats with an epsilon: `std::abs(a.x - b.x) < 1e-9`.
- Not making `operator*` commutative - `Vec2 * double` works but `double * Vec2` gives compile error without the symmetric non-member overload. Always add both: `operator*(Vec2, double)` and `operator*(double, Vec2)`.
- Normalising a zero vector - `length() == 0` causes division by zero in `normalised()`. Always check and handle: throw, return zero vector, or return an error. Here we check `length() < epsilon`.
Tip
Tip
Practice Mini Project Part 6 Vector2D with Full Operator Overloading in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Arithmetic (+, -, *), Compound (+=, -=), Stream (<<, >>), and Equality (==, !=) Pipeline
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 6 Vector2D with Full Operator Overloading from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project Part 6 Vector2D with Full Operator Overloading is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Build a production-quality 2D vector math library with: all arithmetic operators, comparison, stream I/O, subscript, conversion-to-bool, normalise/dot/cross/angle functions, and a Polygon class that uses `std::vector<Vec2>` with overloaded `<<` for printing.
- Floating-point equality with `==` - `a.x == b.x` fails for computed values due to rounding. Always compare floats with an epsilon: `std::abs(a.x - b.x) < 1e-9`.
- Not making `operator*` commutative - `Vec2 * double` works but `double * Vec2` gives compile error without the symmetric non-member overload. Always add both: `operator*(Vec2, double)` and `operator*(double, Vec2)`.
- Normalising a zero vector - `length() == 0` causes division by zero in `normalised()`. Always check and handle: throw, return zero vector, or return an error. Here we check `length() < epsilon`.
Finished this lesson?