Postfix and Prefix Operators
C++ is a language that requires sustained effort of programming for a years , say, the gurus of the language. May be that is the case..Personally , the language is fascinating in terms of design. Just by looking at why some things are done the way they are in C++, the learning can be immense.
For example - Postfix and Prefix operators – i++ and ++i . How do you think such a thing is implemented? As you know that a function is overloaded based on the input parameter types. Did you realize that there is no input parameter , at least, on the surface of it ? Then how does it work ? How does compiler know the difference between ++() prefix and postfix..Well, here is something that one can understand and appreciate how things are done. In the case of postfix, compiler silently passes int 0 as an input and in the case of prefix, no parameter is passed.
In our hurry to program away to glory, sometimes, these little inner circles are missed out by us. Do you know that the return type of postfix is a const type and return type of prefix is a reference type..Why in the world was C++ designed like that ?
Well, answer lies in a simple statement , i++++ is illegal , which most of us agree. Double increment doesn’t work. WHY ? because i++ returns a const and nothing can be done on const
So, you see, there are some differences in the way postfix and prefix is designed : Return values are different, Compiler passes an input silently in one of the operators and there is a creation of temporary object in postfix.
What’s the use of knowing the above stuff ? When you write your own classes, you will keep all these issues in mind when designing your prefix and postfix operators for your custom classes.