Overloading an operator question

Solved
Last edited on
The only thing obviously wrong with it is that it doesn't return what it promises to.
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()?
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.
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.
Solved
Last edited on
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.