Implementing C++ Operators and Overloading for Custom Classes
C++ offers a rich set of built-in operators to various computational tasks including arithmetic, logical, bitwise, and relational operations. A powerful feature allows these symbols to be redefined for user-defined types, enhancing readability and intuitive usage.
Standard Operator Categories
Arithmetic
- Addition (
+) - Subtraction (
-) - Multiplication (
*) - Division (
/) - Modulo (
%)
Relational
- Equal (
==) - Not Equal (
!=) - Greater (
>) - Less (
<) - Greater/Eq (
>=) - Less/Eq (
<=)
Logical
- AND (
&&) - OR (
||) - NOT (
!)
Bitwise
- AND (
&) - OR (
|) - XOR (
^) - NOT (
~) - Shift Left (
<<) - Shift Right (
>>)
Assignment
- Copy (
=) - Compound variants (e.g.,
+=,&=, etc.)
Other
- Dereference (
*) - Address (
&) - Access (
.) - Pointer Access (
->) - Call (
()) - Subscript (
[])
Extending Functionality
To modify operator behavior for custom structs or classes, developers implement special member functions or utilize friend functions.
Arithmetic Redefinition
#include <iostream>
struct Vector2D {
float x, y;
Vector2D(float a = 0.0f, float b = 0.0f) : x(a), y(b) {}
Vector2D operator+(const Vector2D& rhs) const {
return Vector2D(x + rhs.x, y + rhs.y);
}
void print() const {
std::cout << "[" << x << ", " << y << "]" << std::endl;
}
};
int main() {
Vector2D p1(1.0f, 2.0f);
Vector2D p2(3.0f, 4.0f);
Vector2D result = p1 + p2;
result.print();
return 0;
}
Relational Redefinition
#include <iostream>
struct Vector2D {
float x, y;
Vector2D(float a = 0.0f, float b = 0.0f) : x(a), y(b) {}
bool operator==(const Vector2D& rhs) const {
return (x == rhs.x) && (y == rhs.y);
}
void print() const {
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Vector2D a(1.0f, 1.0f);
Vector2D b(1.0f, 1.0f);
if (a == b) {
std::cout << "Match found." << std::endl;
}
return 0;
}
Stream Integration
Friends allow injection into IO streams:
#include <iostream>
struct Vector2D {
float x, y;
Vector2D(float a = 0.0f, float b = 0.0f) : x(a), y(b) {}
friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
os << "(" << v.x << "," << v.y << ")";
return os;
}
friend std::istream& operator>>(std::istream& is, Vector2D& v) {
is >> v.x >> v.y;
return is;
}
};
int main() {
Vector2D input;
std::cout << "Enter values: ";
std::cin >> input;
std::cout << "Data: " << input << std::endl;
return 0;
}