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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 21: Operator Overloading | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 21 of 45

·C++

Lesson 21: Operator Overloading

10 min

Course progress47%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Member vs. non‑member overloads
  • Overloading stream insertion operators
  • Best practices to avoid surprising behavior
  • When not to overload

Operator Overloading

C++ 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.


Example: Vector2D with arithmetic and stream operators

class Vector2D {
    double x_, y_;
public:
    Vector2D(double x = 0, double y = 0) : x_(x), y_(y) {}
    // addition
    Vector2D operator+(const Vector2D& rhs) const {
        return Vector2D(x_ + rhs.x_, y_ + rhs.y_);
    }
    // scalar multiplication (member)
    Vector2D operator*(double scalar) const {
        return Vector2D(x_ * scalar, y_ * scalar);
    }
    // stream insertion for printing
    friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
        return os << '(' << v.x_ << ", " << v.y_ << ')';
    }
};

int main() {
    Vector2D a{1, 2}, b{3, 4};
    Vector2D c = a + b * 2.0; // uses overloaded * and +
    std::cout << \"c = \" << c << '\
';
    return 0;
}

Key guidelines:

  • Prefer non‑member overloads for symmetric operators (+, ==).
  • Never overload operators in a way that breaks expected precedence or associativity.
  • Keep overloads intuitive; avoid surprising side‑effects.

Tip: Overload operator= and the copy/move constructors together to maintain the rule of three/five.


<Alert type="warning">You cannot overload &&, ||, , (comma), or ?:.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 20: Copy Constructor, Assignment Operator, Rule of Three/FiveContinue to lesson 22Lesson 22: InheritanceBack to C++ Course curriculum