Operator Overloading

Overloading Arithmetic Assignment Operators

How can I overload arithmetic assignment operators like += and *= for my custom type?

Abstract art representing computer programming

To overload arithmetic assignment operators like +=, -=, *=, /=, and %= for your custom type, you need to define them as member functions that modify the object itself and return a reference to the modified object.

Here's an example of overloading the += and *= operators for a custom Vector class:

#include <iostream>

class Vector {
 private:
  float x, y, z;

 public:
  Vector(float a, float b, float c)
    : x(a), y(b), z(c) {}

  Vector& operator+=(const Vector& other) {
    x += other.x;
    y += other.y;
    z += other.z;
    return *this;
  }

  Vector& operator*=(float scalar) {
    x *= scalar;
    y *= scalar;
    z *= scalar;
    return *this;
  }

  void print() const {
    std::cout << "(" << x << ", " << y
      << ", " << z << ")\n";
  }
};

int main() {
  Vector v(1.0f, 2.0f, 3.0f);
  Vector u(0.5f, 0.5f, 0.5f);

  v += u;
  v.print();

  v *= 2.0f;
  v.print();
}
(1.5, 2.5, 3.5)
(3, 5, 7)

In this example, we define the += and *= operators as member functions of the Vector class. The += operator adds the components of another Vector object to the current object, while the *= operator multiplies each component of the current object by a scalar value.

Both operators modify the object itself and return a reference to the modified object using *this. This allows for chaining multiple arithmetic assignment operations.

By overloading these operators, we can use the familiar syntax of += and *= with our custom Vector objects, making the code more readable and expressive.

Remember to define the behavior of these operators according to the specific semantics of your custom type.

This Question is from the Lesson:

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved