In this lesson, you will learn about Explicit Conversion in C++, its usage, and examples to better understand the topic.
Explicit conversion occurs when a user explicitly converts data from one type to another. Type casting is another name for this type of conversion. Instead of being done automatically, the type conversion is clearly defined within a program.
In C++, there are primarily three ways to apply explicit conversion. As follows:
Casting data from one type to another can also be done using a function like notation.
Basic Syntax
data_type(expression);
As the name suggests, the C++ programming language prefers this kind of casting. Cast notation is another name for it. This style’s syntax is as follows:
Basic Syntax
(data_type) expression;
Example of Cast notation and Function notation Casting
//Example of Explicit Casting #include <iostream> using namespace std; int main() { float varFloat = 35.12; int varInteger = 0; // C-style conversion from float to integer varInteger = (int) varFloat; cout << "Var Integer: " << varInteger << endl; // function-style conversion from float to integer varInteger = int(varFloat); cout << "Var Integer: " << varInteger << endl; return 0; }
Output
Var Integer: 35 Var Integer: 35
See in the above example that both casting results are the same. It’s just the style of casting.
In addition to these two types of castings, C++ provides four types of conversion operations. The term “type conversion operators” describes them as follows. In later tutorials, we shall discover more about these casts.
Type Conversion Operators
This concludes the C++ Explicit Conversion lesson. In the next lesson, you will learn about Arithmetic Operators in C++.