Overloading an operator question

Nov 1, 2015 at 11:47pm
Solved
Last edited on Nov 5, 2015 at 3:25am
Nov 2, 2015 at 1:15am
The only thing obviously wrong with it is that it doesn't return what it promises to.
Nov 2, 2015 at 1:44am
The function had no return value in the header, am I meant to just return the value I added to the vector?

So something like return test.end()?
Nov 2, 2015 at 5:35am
Assignment operators, and compound assign operators should "return *this;". Meaning they return a non-const reference to the object being worked with.

You would NOT want to return test.end() b/c that would return an iterator (not a Test&) to an invalid element, ie, one past the last valid element, that must never be dereferenced, or even advanced forward/backward.
Nov 2, 2015 at 9:11am
It is ok to write it like so:
1
2
3
4
5
6
	void Test::operator += (const TestX& t){
	  this->testAdd(&t);

	//Test& Test::operator += (const TestX&){ Is it possible to do it like this as well? I have a feeling this is the correct way...
	 //   this->testAdd(...);
	}


The problem with your code is that you don't know anything about the life time of t. It could be a stack element and then you might have an invalid/dangling pointer.
Nov 2, 2015 at 10:39pm
Solved
Last edited on Nov 5, 2015 at 3:25am
Nov 3, 2015 at 7:52am
Yes, you may write this:
1
2
3
4
5
Test& Test::operator += (const TestX& t){
	  this->testAdd(&t);

	  return *this;
	}


The reason for this is that you can cascade the operator: a += b += c;

This way you can do it with the basic types in c. I don't want it hence I'm using void as the return type.
Topic archived. No new replies allowed.