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