Reputation:
In the example below, the addition operator has been overloaded:
class CVector {
public:
int x,y;
CVector operator + (const CVector&);
};
BUT would you say that the addition operator is overloaded for the type CVector, when the addition operator hasn't even been declared or defined before in this class?
Thanks!
Upvotes: 0
Views: 57
Reputation: 206577
would you say that the addition operator is overloaded for the type CVector, when the addition operator hasn't even been declared or defined before in this class?
Yes.
Let's say you have:
int a = 10;
int b = 20;
If you use a + b
, you are using a version of the +
operator that is defined for int
s.
Now, let's say you have:
std::string as;
std::string bs;
If you use as + bs
, you are using a version of the +
operator that is defined for std::strings
s. For this reason, this +
operator is an overload that works with std::string
s.
Coming to your class, let's say you have:
CVector v1 = { ... };
CVector v2 = { ... };
When you define a function that allows you to use v1 + v2
, it is an overload of the +
operator that works with CVector
s.
It is not an overload of the +
operator for CVector
s.
It is an overload of the +
operator that works with CVector
s.
Upvotes: 1
Reputation: 35154
cppreference defines operator overloading briefly as
operator overloading: Customizes the C++ operators for operands of user-defined types. Overloaded operators are functions with special function names.
So operator +
actually is a function with a predefined name operator+
, which is already in use for several types. When you now provide a custom implementation of operator+
for your user-defined type CVector
, then this is seen as overloading
, because you define a different implementation for a given function name for individual parameters.
Upvotes: 2