Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 14 of 45 · C++

Lesson 21: Operator Overloading

Duration: 10 min

Operator Overloading\n\nC++ lets you give existing operators new meaning for your own types, making them behave like built‑in types. Overloadable operators include arithmetic, comparison, subscript, function call, and stream insertion/extraction.\n\n---\n\n## Example: Vector2D with arithmetic and stream operators\ncpp\nclass Vector2D {\n double x_, y_;\npublic:\n Vector2D(double x = 0, double y = 0) : x_(x), y_(y) {}\n // addition\n Vector2D operator+(const Vector2D& rhs) const {\n return Vector2D(x_ + rhs.x_, y_ + rhs.y_);\n }\n // scalar multiplication (member)\n Vector2D operator*(double scalar) const {\n return Vector2D(x_ * scalar, y_ * scalar);\n }\n // stream insertion for printing\n friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) {\n return os << '(' << v.x_ << ", " << v.y_ << ')';\n }\n};\n\nint main() {\n Vector2D a{1, 2}, b{3, 4};\n Vector2D c = a + b * 2.0; // uses overloaded * and +\n std::cout << \"c = \" << c << '\\n';\n return 0;\n}\n\n\nKey guidelines:\n- Prefer non‑member overloads for symmetric operators (+, ==).\n- Never overload operators in a way that breaks expected precedence or associativity.\n- Keep overloads intuitive; avoid surprising side‑effects.\n\n> Tip: Overload operator= and the copy/move constructors together to maintain the rule of three/five.\n\n---\n\n<Alert type="warning">You cannot overload &&, ||, , (comma), or ?:.

Previous: Lesson 20: Copy Constructor, Assignment Operator, Rule of Three/FiveNext: Lesson 22: Inheritance