Operator Overloading

Write your question here.
Hey everyone, i need to write an operator overloading for ++ in two ways, a++ and ++a. But i am not sure i wrote the declarion of the two function right. Can you tell me please if it's ok?

1
2
3
4
5
6
7
8
9
10
	//(++a)
		Iterator& operator++(){ 
			if (m_iter = m_iter -> m_next != NULL)
			{
				m_iter = m_iter -> m_next;
				return m_iter; 
			}
			else
				return false;
		}


1
2
3
4
5
6
7
8
9
10
11
	//(a++)
		Iterator& operator++(){
			if (m_iter = m_iter -> m_next != NULL)
			{
				Iterator* tmpr = m_iter;
				m_iter = m_iter -> m_next;
				return tmpr;
			}
			else
				return false;
		}
I think that you did not mean

if (m_iter = ( m_iter -> m_next != NULL) )

in the statement

if (m_iter = m_iter -> m_next != NULL)

did you?
No.
In first: false is not a reference to Iterator. You should return valid reference everytime. In other case it is compile-time error.

Second: overload of postfix iterator should look like: Iterator& operator++(int)
Also it should return copy of curent iterator in every case.

Read about recommended operator semantic.
for example x = y++ should be equivalent to x = y, ++y
Last edited on
yes, thanks, I didn't even noticed that mistake! But what i wanted to know is, how the compiler can know which function to go to, if the declarions are the same?
@MiiNiPaa


I think that this

Iterator& operator++(int)

is a typo.

must be

Iterator operator++(int)
Yes, I just have copied his code and added int. Correct declaration:
1
2
Iterator& operator++()    //++a
Iterator  operator++(int) //a++ 
Declaration are not the same postfix operators should have dummi variable in their declaration
http://www.learncpp.com/cpp-tutorial/97-overloading-the-increment-and-decrement-operators/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
Iterator & operator ++() 
{
	m_iter = m_iter -> m_next;
	return ( *this );
}

Iterator operator ++( int ) 
{
	Iterator it = *this;
	m_iter = m_iter -> m_next;
	return ( it );
}
Last edited on
Thanks everyone for the help!
Topic archived. No new replies allowed.