Jump to content


vernonglenn

Member Since 02 Aug 2012
Offline Last Active Aug 06 2012 10:02 PM
-----

Topics I've Started

Overloading Prefix/Suffix Increment Operators (c++)

02 August 2012 - 11:30 PM

Hello all,

So I'm trying to learn programming on my own and I'm sort of stuck on overloading increment operators. I don't understand how the compiler can distinguish between which member function to use in the given example (from a book I'm reading):

Quote

#include <iostream>
using namespace std;
#include <string>
typedef unsigned short USHORT;
class Counter
{
public:
Counter();
~Counter(){}
USHORT GetItsVal()const { return itsVal; }
void SetItsVal(USHORT x) {itsVal = x; }
//const Counter& operator++ (); // prefix
const Counter operator++ (int); // postfix
private:
USHORT itsVal;
};

Counter::Counter():
itsVal(0)
{}
/*
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
*/
const Counter Counter::operator++(int)
{
Counter temp(*this);
++itsVal;
return temp;
}


int main() {
Counter i;
cout << "The value of i is " << i.GetItsVal() << endl;
i++;
cout << "The value of i is " << i.GetItsVal() << endl;
++i;
cout << "The value of i is " << i.GetItsVal() << endl;
Counter a = ++i;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
a = i++;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
system("PAUSE");
return 0;
}

I would understand if instead of "a = i++;" the line read "a = i++(1);" , that way it shows explicitly it's a call to the function that takes a parameter, but the above code works just fine in visual c++. I suppose it could be the return type, but I thought you couldn't overload functions by return type


Thanks in advance