> For the complete documentation index, see [llms.txt](https://python-self-driving.gitbook.io/self-driving/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://python-self-driving.gitbook.io/self-driving/c++/overload-in-c++.md).

# Overload in C++

**What is the difference and why do both ways work?**

In practice, both i++ and ++i will give you the same results; these are a shorthand way of writing i = i + 1. The difference between the two is subtle.

```
int i = 5;
int x = i++; // x = 5, i = 6 (called postfix)
int x = ++i; // x = 6, i = 6 (called prefix)
```

In both cases, the i variable increases by 1. In the postfix case, i++, int x = i is evaluated first and then i = i + 1 occurs.

In the prefix case, ++i, i = i + 1 occurs first and then int x = i executes.

Many code guidelines recommend using ++i over i++. In reality neither one is more efficient than the other when using integer variables.

However, there is a difference when you write a C++ class that overloads the ++ operator. You saw operational overloading in the Python matrix project; the code overloaded mathematical signs to carry out matrix addition, subtraction, multiplication, etc.

When overloading the postfix operator, C++ needs to keep track of two values. In the example, the values would be 5 and 6. For the prefix operator, C++ only needs to keep track of one value: 6. Hence, when overloading the ++ operator, it's generally more efficient to use prefix than the postfix.

Overloading is an advanced C++ topic that isn't covered in depth here. If you'd like to learn more, here are a few resources:

[Stackoverflow](https://stackoverflow.com/questions/3846296/how-to-overload-the-operator-in-two-different-ways-for-postfix-a-and-prefix)

[IBM Knowledge Center](https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.cbclx01/cplr330.htm)
