## Conversions

Most people when they start to learn any strictly-typed programming language encounter a similar dilemma: If there are different types of numbers (integers, floats, etc.), how can I change between those? Maybe the most important example is the integer division. If you really wanted to get a float value out of it, how would you do it? That’s where

**conversion**, or**casting**comes into play.Casting is a process of converting one data type into another. So, in the example where we had 7 / 2, how could we get the result 3.5 instead of 3? We would use something called explicit casting. It is done by putting a pair of brackets in front of the value that needs to be casted and inside the brackets putting the data type we want the value to be casted into. Keep in mind that if you want to store the newly casted value, the variable you are storing it into must be the same type as the cast.

```
int a = 7;
int b = 2;
float c = (float)a / b; // Casting "a" into float (a = 7.0) and then divide by 2. Result: c = 3.5
```

It is logical to assume that we can cast integers into rational numbers (the set of rational numbers contains the set of integers), but what about the other way around? It is the same as in integer division. The floats decimal points get cut off and we’re left with just the whole integer part.

Maybe the most interesting thing about casting is that any primitive data type can be casted into another primitive data type.

```
float x = 3.4;
int y = (int)x; // x = 3
double a = 4.7;
long b = (long)a; // b = 4
```

There is another way of casting called **implicit casting**. It is done automatically by the compiler whenever it is possible, without any human effort. The compiler has its own predefined rules based on how to implicitly convert one data type into another. There is a hierarchy of data types and it is only allowed to implicitly convert lower data type into higher data type.

Implicit conversion will not take place if you try converting a higher type into a lower one. In that case, you would need to convert the data types explicitly, but keep in mind that when using explicit conversion, there will be a possible data loss.

```
int a = 3;
float x = 3.4 + a; // 6.4
int val = 'a' - 3; // 94 - 'a' is an ASCII character with a value of 97
int b = (int)x - a; // 3
float y = b + a; // 6.0 - data loss
double final_result = a * x - b * y; // 1.2
```

## Table of contents

- Loops, Pointers and Functions
- Classes and Objects
- Operator Overloading
- Class Inheritance
- Exceptions
- Namespaces
- Templates
- Standard Library
- Additional Problems