Labs ICT
Pro Login

Operator Overloading

1 min read | C++ Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Operator Overloading

Operator overloading lets you define custom behavior for operators like +, -, *, etc. when used with user-defined types.

Syntax

Define a function with the keyword operator followed by the operator symbol. It can be a member function or a friend function.

#include <iostream>
using namespace std;

class Vector {
public:
  double x, y;

  Vector(double x, double y) {
    this->x = x;
    this->y = y;
  }

  Vector operator+(const Vector& v) {
    return Vector(x + v.x, y + v.y);
  }

  void display() {
    cout << "(" << x << ", " << y << ")\n";
  }
};

int main() {
  Vector v1(1.5, 2.5);
  Vector v2(3.0, 4.0);
  Vector v3 = v1 + v2;
  v3.display();
  return 0;
}