Awful, Awful C++: Operator Overloading Insanity
Ew! This is an emergency post. I just found out about some operator overloading brain damage in C++. Take a look at the Wikipedia article about Operators in C and C++. Just to make sure, I checked the C/C++ Language Reference for IBM’s XL C++ compiler (I find it easier to read than many of the other language references).
As you are no doubt aware, C++ has a ++ prefix and a ++ postfix operator (there is also the decrement operator but the same insanity applies to it). They work differently so when overloading them, there is a need for two different functions.
The syntax for operator overloading does not however allow for the difference in a obvious way. operator++ doesn’t seem to indicate whether you are talking about the prefix or the postfix variant. Here’s a code snippet that shows the syntax for both:
class X { void operator++() { }; void operator++(int) { }; };
Do you see the difference? The postfix variant uses a dummy int argument. What?!
C++ is even worse than that! I found out that there are two more operators that C++ has. Here’s an example of how they might be used:
struct X { int *foo; }; void foo(struct X *p) { p->*foo = 1; } void bar(struct X &p) { p.*foo = 1; }
Do you see it? Do you see that abomination? Here’s the equivalent version using a more mainstream syntax.
void foo(struct X *p) { *p->foo = 1; } void bar(struct X &p) { *p.foo = 1; }
We’ve tried to compile a test program that uses this “fancy” notation, but gcc does not like it. I am glad.
Comment by unknown — January 1, 1970 @ 00:00