Creating Custom Operators

Can I create new operators that don't exist in C++? Like ** for exponentiation?

No, C++ does not allow you to create new operators - you can only overload the existing ones. Here's a complete list of operators you can overload, and some alternatives for when you need custom operations:

#include <cmath>
#include <iostream>

struct Vector3 {
  float x, y, z;

  // We can overload existing operators
  Vector3 operator+(const Vector3& other) const {
    return Vector3{
      x + other.x, y + other.y, z + other.z
    };
  }

  // But we can't create a ** operator for power
  // Instead, we create a named function
  Vector3 pow(float exponent) const {
    return Vector3{
      std::pow(x, exponent),
      std::pow(y, exponent),
      std::pow(z, exponent)
    };
  }
};

int main() {
  Vector3 vec{2.0f, 3.0f, 4.0f};

  // This works - using existing operator
  Vector3 sum{vec + vec};

  // This won't compile - ** isn't a valid operator
  Vector3 powered{vec ** 2.0f};  

  // Instead, use the named function
  Vector3 squared{vec.pow(2.0f)};

  std::cout << "Squared: " << squared.x
    << ", " << squared.y
    << ", " << squared.z << "\n";
}
error: invalid operator **

The operators you can overload in C++ include:

  • Arithmetic: +, , , /, %
  • Compound assignment: +=, =, =, /=, %=
  • Comparison: ==, !=, <, >, <=, >=
  • Increment/Decrement: ++, -
  • Member access: >, []
  • Function call: ()
  • Bitwise: &, |, ^, ~, <<, >>

For operations that don't map to existing operators, you should create well-named member functions or free functions instead. This often leads to more readable and maintainable code anyway!

Operator Overloading

This lesson introduces operator overloading, a fundamental concept to create more intuitive and readable code by customizing operators for user-defined types

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Use Operator Overloading?
Why do we need operator overloading when we could just create regular functions like AddVectors() or MultiplyVectors()?
Overloading With Different Types
Can we overload operators to work with different types? For example, could I multiply a Vector3 by a float instead of just an int?
Parameter Order in Operators
Does the order of parameters matter in operator overloading? Like, is (Vector3, int) different from (int, Vector3)?
Unconventional Operator Behavior
Can I overload operators to do completely different things than what they normally do? Like making + do multiplication?
Operators Across Different Types
Can I use operator overloading with custom types from different classes? Like adding a Vector3 to a Point3D?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant