user7982333
user7982333

Reputation:

Why are you overloading an operator that has not been defined before?

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

Answers (2)

R Sahu
R Sahu

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 ints.

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::stringss. For this reason, this + operator is an overload that works with std::strings.

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 CVectors.

It is not an overload of the + operator for CVectors.
It is an overload of the + operator that works with CVectors.

Upvotes: 1

Stephan Lechner
Stephan Lechner

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

Related Questions