Here's a breakdown:
The built-in C++ operators normally only work on basic data types like 'int'. For example:
1 2
|
int myvar;
myvar = 3 + 5; // <---
|
The marked line will use the '+' operator to add 3 and 5 together (which it can do because they're both of type 'int'), it will then use the '=' operator to assign the result (8) to 'myvar'.
This only works because 'int' is a fundamental type of the language. If you were to make a class called MyInt, it wouldn't work. Example:
1 2 3 4 5 6 7 8 9 10 11
|
class MyInt
{
public:
int v;
};
//-------------
void func()
{
MyInt myvar;
myvar = 8; // error
}
|
Because myvar is a
MyInt
object and not a fundamental type, this code produces an error because the compiler can't assign the 8 (an 'int') to myvar (a 'MyInt').
Operator overloading lets you define how operators work with a specific class. So for example if we wanted the above to work, we could overload the = operator to accept an int:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class MyInt
{
public:
int v;
MyInt& operator = (int i) // overload the = operator
{
v = i;
return *this;
}
};
//---------
void func()
{
MyInt myvar;
myvar = 8; // now this works okay!
}
|
A few things to note about operator overloading:
- You can only do it with user defined types (ie: classes).
- You don't
have to be intuitive with the operators, but you should be. IE: it's legal to overload - so that it performs addition instead of subtraction, but you should never do that because it makes your code hard to follow.
- You can
NOT overload operators for built in types. At least
one of the operands must be a user defined type. Therefore:
1 2 3 4 5
|
int blah = 5 + 6; // CANNOT overload this + because '5' and '6' are both
// built in types (int)
int blah = MyInt(5) + 6; // CAN overload this + because 'MyInt' is a
// user defined type
|