View Full Version : C++ Operator Overloading - Reference?
magicyte
11-26-2008, 05:37 AM
In the following C++ class:
class Counter
{
public:
Counter();
~Counter();
int GetItsVal(void) const { return itsVal; }
void SetItsVal(int x) { itsVal = x; }
void Increment(void) { ++itsVal; }
const Counter& operator++ ();
private:
int itsVal;
};
Counter::Counter():
itsVal(0)
{}
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
Why is the operator++ overloader a reference and not regular w/out the & (ampersand)?
Explaination of how operator overloading works would also be acceptable. Thanks in advance.
-magicyte
It's a reference because if it weren't the object would be passed by value, which would involve creating a whole new instance of a potentially huge object.
Operator overloading simply allows you to define the behaviour of existing built-in operators on your class. It's implemented in the form of a method <your class>::operator<relevant operator>, and types are pretty much intuitive — e.g.
const T T::operator+(const T &rhs);
T& T::operator=(const T &rhs);
T& T::operator!();
bool T::operator==(const T &rhs);There are (surprisingly for C++) only a couple of ugly hacks and weird gotchas to look out for:
T& T::operator++(); // this is prefix (++foo)
T& T::operator++(int unusedIntParameter); // this is postfix (foo++)(applies to -- as well).
magicyte
11-26-2008, 06:32 PM
It's a reference because if it weren't the object would be passed by value, which would involve creating a whole new instance of a potentially huge object.
Oh! I remember now! In my C++ book, it talked about making a reference for something so that a whole new object wasn't to created (in other words, a reference to the current object). Didn't get it, but after HOURS //more like minutes! of thinking, it registered (though it was tough on my mind :D).
Just been trying to learn about operator overloading, and finally figured more that half of it out, thanks to you. :)
Why does the overloaded '++' function in Counter return the this pointer? And what is the this pointer's value in this case?
-magicyte
this is what it always is: a pointer to the object on which the method is being invoked. ++ returns a reference (note that the pointer is dereferenced) because that's what the operator does: increments its operand and then returns the incremented operand.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.