Quick Answer
Define custom behavior for operators.
Understanding the Issue
C++ allows defining custom implementations for most operators when working with user-defined types.
The Problem
This code demonstrates the issue:
Cpp
Error
// Need to add two custom objects
The Solution
Here's the corrected code:
Cpp
Fixed
#include <iostream>
class Vector2D {
public:
float x, y;
Vector2D(float x, float y) : x(x), y(y) {}
// Overload + operator
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
};
int main() {
Vector2D v1(1.0f, 2.0f);
Vector2D v2(3.0f, 4.0f);
Vector2D result = v1 + v2; // Uses overloaded +
std::cout << "Result: (" << result.x << ", " << result.y << ")" << std::endl;
return 0;
}
Key Takeaways
Operator overloading enables natural syntax for custom types.