• 0

[C++] Overloaded Operator Associativity


Question

If I overload an operator, such as <<, what will be the associativity?

For my tests I used a simple class, defined as:

class Complex {
 Complex(float re = 0, float im = 0) {
   real = re;
   imag = im;
 }
 const Complex &amp; operator=(const Complex&amp; c) {
   if (this != &amp;c) {
	 real = c.real;
	 imag = c.imag;
   }
   return *this;
 }
 ostream&amp; operator &lt;&lt; (ostream&amp; out, const Complex&amp; z) {
   z.show(out);
   return out;
   ...
 }
};

My tests have shown that operator<<(ostream& out, const Complex& z) is left-to-right associative, as is usual for the << operator. Also, operator=(const Complex &c) is right-to-left associative, as is normal for the = operator.

This leads me to believe that the associativity of my overloaded operators is based on the associativity of the default operators (or that the actual symbols used specify associativity, and not the function itself). My lecturer however, tells me that the associativity is decided by the compiler based on the return types of the overloaded operators.

Which is correct?

(or, if I've explained it poorly, just answer: How is the associativity for overloaded operators determined?)

Thanks for your help.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I've never heard of compiler specific associativity.

That's not really what I was getting at..

My lecturer tells me that the compiler decides based on the return types of the operators. This does not necessarily have to be compiler specific. This doesn't really make sense to me as I dont believe C++ would be written in a way that makes it unclear which operators would be invoked first.

Just to clarify, if I overload the << operator with any function, any return type, it should still be left-to-right associative, correct?

And similarly, if I overload the = operator, it should still be right-to-left associative?

Link to comment
Share on other sites

  • 0

The lecturer is wrong. associativity and precedence of operators is always the same, regardless the type.

The C++ FAQ seems to agree with that:

The names of, precedence of, associativity of, and arity of operators is fixed by the language.
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.