I’ve seen some people reference “overloading” an operator but I don’t quite understand what it means. Can anyone please explain this clearly for me?
Thanks for your help.
I’ve seen some people reference “overloading” an operator but I don’t quite understand what it means. Can anyone please explain this clearly for me?
Thanks for your help.
Overloading an operator, is like to give a meaning to it.
For example when we take a ‘==’ (equals) operator, and apply it to two integers
Whenever you see an expression like
if(2 ==3) {
}
compiler sees it in this way:
if(2.operator==(3)) {
}
This is called ‘Syntactic sugar’. It would be really tedious for a programmer to every time write code like this
if(2.operator==(3)) {
}
So when we write ‘==’ compiler understands that it really means ‘operator==()’
So now if we would define the ‘==’ operator for int like this:
bool operator==(int a, int b) { if(a == b) return true; else if (a != b) return false. }
Now we can use it in simple expressions like
4 == 5 -> this returns false
5 == 5 -> this returns true.
Operators for simple data types like integers or floats or chars are implemented by language, and so
you don’t need to define them.
But when you create your own data types, (classes) you as a class creator have to give a meaning to a == operator.
If for example you have a, let’s say Car class. What would it mean to you to say that one car equals to another one?
classs Car {
string engineType;
int amountOfWheels;
string color;
bool operator==(Car const &car1, Car const &car2);
}
bool Car::operator==(Car const &car1, Car const &car2) {
return car1.engineType == car2.engineType && car1.amountOfWheels == car2.amountOfWheels;
}
In this case you would say that one car equals to another one when engine and amount of wheels are equal.
So this is regarging only ‘==’ operator.
There are other kind of operators like ‘int’ , ‘char’, ‘bool’ and others, and you could overload them too, if it makes sense to you.
You could for example overload bool operator, and now, whenever you have an ‘if’ expression, you could use your car.
Car {
string engineType;
operator bool() const {
if(engineType != "")
return true;
else
return false;
}
};
And now if you have code like this:
Car car1.
You can use it like this:
if(car1) {
// do something with your car
}
Note plese. Normally you do not overload operators like ‘int’ ‘bool’ ‘float’ and others. I just show it here as an example. Overloading this operators could cause you errors that would be really hard to find.
Compiler could start treating your car as bool in places where you would never expect.
Normal practice is only to overload the ‘==’ operator.
Update: I tried to make it as explicit as possible. Hopefully this helps. If you have more questions, or something is not clear, ask please, and i will try to explain better.
Useful link on the topic: http://en.cppreference.com/w/cpp/language/operators
Hi Maxim, thank you for your explicit and detailed description. I appreciate your efforts very much however it’s still way over my head. I’m not experienced with code much. Assume I know as much as has been taught up to this lesson.
I’m going to take a stab at understanding and explaining what you’ve shared. Let me know where I’m wrong.
Is overloading essentially redefining how a standard operator (keyword) works? Or is it an operator that is defined in two or more namespaces or even a namespace we’ve made? I’m starting to step out of my area of understanding now so that may not have made sense.
And now to really jump in the deep end, is it redefining the operator in a prototype ( if I’m using that term correctly, that is a function in an object’s parameters?) Maybe I’m talking gibberish.
Thanks again for your time and patience.
Hey again
In C++ ‘namespace
’ keyword actually had certain meaning, so i am not sure if you are trying to refer to it or no.
With this, i think you are getting it right. I will try a different approach on explaining this. It is a bit hard to base my explanation on ‘What has been taught up till this lesson’, because the classes have not been introduced yet. But i will try anyway.
This time we’ll take a operator++()
as an example;
Having following code:
int main() {
foat a = 2.0;
int b = 4;
a++;
b++;
}
When compiler goes line by line reading your code:
He knows that:
float a = 2.0
// means create variable of type float in memory and initialize it with value 2.0;
float b = 4
//means create variable of type int and initialize it with value 4;
now
a++
// Has a meaning to a compiler, and he knows that this means [Take value stored in ‘a’, increment it by 1, and store it back; ‘a’ now holds value 3.0]
b++
//Same. ]Take value in ‘b’, increment it by 1, store it back in ‘b’; ‘b’ now holds value 4]
How does compiler knows what to do when he sees a++
or b++
? It is because internally, operator++()
is defined for class int and float;
Later on in Bulls and cows part of the course, you will be introduced to a class called ‘FBullCowGame’. This class has some private members. It also has some methods defined.
Imagine now a program like this:
class FBullCowGame
{
bool IsGameWon() const;
EGuessStatus CheckGuessValidity(FString) const;
FBullCowCount SubmitValidGuess(FString);
private:
int32 MyCurrentTry;
int32 MyMaxTries;
FString MyHiddenWord;
bool bGameIsWon;
}
int main () {
FBullCowGame game;
game++;
}
When compiler sees line
game++;
Compiler does not know what to do in this case. Should he increment MyCurrentTry
? MyMaxTries
? Should he call IsGameWon()
method?
So it is your responsibility to tell him what do you mean by that.
You decided that game++
should mean to increase MyCurrentTry
value;
All you have to do is to overload a ‘++’ operator.
Something like this:
class FBullCowGame
{
bool IsGameWon() const;
EGuessStatus CheckGuessValidity(FString) const;
FBullCowCount SubmitValidGuess(FString);
operator++() {
MyCurrentTry++;
}
----------
rest of your class
}
I hope that would help you a bit more wit understanding of this topic.
Please ask as many questions as you need until you completely understand it.
I will answer them gladly.
Note please that this topic touches the classes topic, and i am not sure if you are familiar with it or no.
If no, then operators overloading might become more clear when you study classes and OOP a bit more.
Hey Maxim,
Thanks for making it simpler. It’s starting to make more sense now. The class you provided was a bit confusing to try to read for me but I mostly understood what you were meaning.
I haven’t reached the Class part of the course yet so hopefully, I’ll get a clearer understanding of it in that context.
Just some questions to get a better understanding:
Is operator++() the same as ++?
Where does operator++() come from as in where are you calling it from?
I might be misunderstanding the code but where does game (from game++) come from in the code? Is that the line before? If so I don’t understand the syntax yet.
Is overloading just adding new functionality to an operator that is only relevant in a certain context like a class or function?
Thanks again for your help.
Hey Mitchell!
Well, it’s not that it is the same as '++'
. IT IS '++'
I’ll give you more examples:
Imagine you wrote next code: (The code makes no sense itself, i wrote it just for the sake of an example)
int main() {
int a = 2;
int b = 3;
if(a == b) { // here we have a '==' operator
cout << "a equals b"; // here we have a '<<' operator
}
a++; // here we have '++' operator
b = a; // here we have '=' operator
int c = 1;
c *= a; // here we have a '*=' operator
}
What really happens behind the scenes, what compiler really sees is this:
int main() {
int a = 2;
int b = 3;
if(a.operator==(b)) {
cout.operator<<("a equals b");
}
a.operator++();
b.operator=(a);
int c = 1;
c.operator*=(a);
}
It would be really tedious for a programmer to write code as in a second example.
But, what actually ‘operator’ is, is just a member function of a class.
(I forgot to mention, that types like int, float, bool, they are also classes in c++, that is why they have these functions/operators in them)
Since in C++ basically almost everything is a class, I would suggest you proceed a bit with the course, until you start learning about classes, and this things would become more clear for you, and also I’ll be able to give you more sophisticated examples
If you wish, we could get on skype, and i can try to answer all your questions with voice.
Hey Maxim,
I’ve started some of the class videos now and while it seemed a little complicated to start with it cleared up a lot of stuff for me. I had some preconceptions of what a class was, which turned out to be incorrect or at least different.
Your response this time has helped me understand it even more. Especially when you said that types like int, float, bool are also classes.
I’ve done a bit of Javascript in the past couple of years and recognised the syntax “a.b();” Am I correct that this is accessing the “b” function from the “a” class?
If this is the same in most languages, then I’ve been misunderstanding how this all works having only learned by trial and error. I only understood the “a.b()” syntax to be accessing part of an object that was predefined as a “prototype” or template somewhere unknown to me (I assumed there was some foundation that was the base level of C++ that couldn’t be changed).
I’ll continue the course and hopefully everything will become perfectly clear in time. If I have any more trouble understanding this I’ll reply again or skype.
Thanks Maxim.