Question about overloading the prefix operator

Started by
4 comments, last by Pixel_Sticks 17 years, 9 months ago
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. :(
Advertisement
overloading the prefix operator is quite simple:
class MyClass{int val;public:// Prefix formMyClass &operator ++() { ++val; return *this;}// Postfix formMyClass &operator ++(int) { val++; return *this;}};

The fake int argument tells the compiler it is the postfix form.

The reason the destructor is called twice in you sample is that you are making and returning a copy of your object in your operator ++(). You should be modifying the object directly, and returning a reference to it, as I am doing in the code sample above.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Edit: i'm too slow... :/
Swift

Sorry im a bit confused by the example. The part "return *this;" isnt discussed until a few pages up and im trying to wrap my head around understanding the general idea before learning to optimize it.

Thanks though
Thanks for the reply Paulius. I think I understand the deconstructor calls now.
Quote:Original post by Paulius Maruska
Edit: i'm too slow... :/



no way man

Im glad I got to read your reply before you edited it. Im sure swiftcoder provided a good example its just that it was a little too high level for me. I just started reading this book two weeks ago and my brain is getting overloaded I think.

Thanks to both of you!

This topic is closed to new replies.

Advertisement