Prefix Versus Postfix Operators

You can use both — and ++ as prefix and postfix operators. When applied to primitives such as int or char, they are indistinguishable in terms of efficiency. When applied to objects, on the other hand, the overloaded prefix operators are significantly more efficient than the postfix ones. Therefore, whenever you’re free to choose between postfix or prefix operators of an object, you should prefer the latter:

 Void f() {Date d1, d2;d1++;  d2--  //inefficient: postfix operator++d1;  --d2;  //prefix is more efficient}

The reason is that the postfix version usually involves a construction of an extra copy of the object, in which its state is preserved, whereas the prefix version is applied directly to its object:

 class Date{Date operator++(int unused) {  // Date++ is less efficientDate temp(*this); //create a copy of the current objectthis.AddDays(1); //increment  current objectreturn temp; //return by value a copy of the object before it was incremented}Date& operator++() {  // ++Date is more efficientthis.AddDays(1); //increment  current objectreturn *this; //return by reference the current object}		   };
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: