Operator Overloading

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!

This Question is from the Lesson:

Operator Overloading

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

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

This Question is from the Lesson:

Operator Overloading

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

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% 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.

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