I have been reading a C++ book and I am trying to understand the concept of overloading the prefix operator. I have read about overloading functions and how they could have the same name if their parameter lists were different. That I understood. Now it is talking about overloading the prefix operator except my understand is there would be different functions with the same name so im a little confused.
Here is the program that has me scratching my head.
#include <iostream>
using namespace std;
class Counter
{
public:
Counter();
~Counter() {}
int GetItsVal() const {return itsVal;}
void SetItsVal(int x) {itsVal = x;}
void Increment() {++itsVal;}
Counter operator++ ();
private:
int itsVal;
};
Counter::Counter(): itsVal(0)
{}
Counter Counter::operator++()
{
++itsVal;
Counter temp;
temp.SetItsVal(itsVal);
return temp;
}
int main()
{
Counter i;
cout << "The value of i is " << i.GetItsVal() << endl;
i.Increment();
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 is: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
return 0;
}
Also in my program I added a cout line to the destructor to help me a little and I see that when this function returns the destructor is called twice and im not sure why.
Counter Counter::operator++()
{
++itsVal;
Counter temp;
temp.SetItsVal(itsVal);
return temp;
}
Im very confused overall by this program. :(