Increment/decrement operators

From Cppreference

Jump to: navigation, search

Increment/decrement operators increments or decrements the value of the object.

Operator name Syntax Over​load​able Prototype examples (for class T)
Inside class definition Outside class definition
pre-increment ++a Yes T& T::operator++(); T& operator++(const T &a);
pre-decrement --a Yes T& T::operator--(); T& operator--(const T &a);
post-increment a++ Yes T& T::operator++(int); T& operator++(const T &a, int);
post-decrement a-- Yes T& T::operator--(int); T& operator--(const T &a, int);
Notes
  • All operators usually return a value of type T. However, essentially any type can be returned (including void,
    i.e. no return value), yet this is unintuitive and thus defeats the purpose of the operators.
  • The int parameter is a dummy parameter used to differentiate between pre- and post- in versions of the operators.

[edit] Explanation

pre-increment and pre-decrement operators increments or decrements the value of the object and returns the resulting value.

post-increment and post-decrement operators increments or decrements the value of the object and returns the value of the object before the operation. Because a temporary copy of the object is made during the operation, for efficiency reasons it is better to employ pre-increment or pre-decrement operators in contexts where the returned value is not used.

[edit] See also

Operator precedence

Common operators
assignment increment
decrement
arithmetic logical comparison member
access
other
a = b

a = rvalue
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a

--a
a++
a--

+a

-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a

a && b
a || b

a == b

a != b
a < b
a > b
a <= b
a >= b

a[b]

*a
&a
a->b
a.b
a->*b
a.*b

a(...)

a, b
(type) a
? :

Special operators

static_cast converts one type to another compatible type
dynamic_cast converts virtual base class to derived class
const_cast converts type to compatible type with different cv qualifiers
reinterpret_cast converts type to incompatible type
new allocates memory
delete deallocates memory
sizeof queries the size of a type
sizeof... queries the size of a parameter pack (C++11 feature)
typeid queries the type information of a type
noexcept checks if an expression can throw an exception (C++11 feature)
alignof queries alignment requirements of a type (C++11 feature)