Hi, I'm studying operator overloading through C++ the complete referece and I've got some questions.

In the book, the author writes this:

loc loc::operator++()
{
	++longitude;
	++latitute;

	return *this;
}

This creates a new object and returns it.

1.Wouldn't it be more efficient to return a reference?
2.This overloads the prefix increment operator, how can I overload the postfix?
3.The author also shows how to accomplish this using friend functions.

loc operator++(loc &l)
{
	l.longitude++;
	l.latitute++;

	return l;
}

Again, wouldn't it better to return a reference?
Is there a benefit to use friend functions here?

Recommended Answers

All 7 Replies

This is the stupidest use of operator++ I've ever seen.

In order:

1) Yep 95% of the time, the thing to do is return a reference. It is not obligatory, for example you could return a flag (for example on a cyclic counter as it loops over)

2)

loc& operator++();      // prefix
        loc& operator++(int);      // postfix

Note that you do nothing with the int e.g. you write

loc&
loc::operator++(int)
{
  // stuff
   return *this;
}

3) I very very much doubt you want a friend function. If they are the same class then you have automatic access anyway. I will also say that version 3 is very strange. The code as given will not work. operator++ MUST take nothing or an int.

If you want a bit more help with (3), then a little more pseudo code explaining what you are actually trying to achieve would help a lot I think.

Hope this helps.

This is the stupidest use of operator++ I've ever seen.

Why?

------------

@StuXYZ

Yes it does, thanks a lot. I'm not trying to do anything, just to understand :D

It doesn't make much sense for a location (specified as latitude and longitude) to support an increment (or decrement) operator at all.

The current implementation causes the location to move in a diagonal direction, what is the benefit? How would it be used?

It doesn't make much sense for a location (specified as latitude and longitude) to support an increment (or decrement) operator at all.

The current implementation causes the location to move in a diagonal direction, what is the benefit? How would it be used?

This is just used to show how it's done :)

But that is exactly why he said 'This is the stupidest use of the ++ operator I've ever seen' because it doesn't serve any useful purpose.

Oh ok that's fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.