Type Conversion in C++
Type
Conversion in C++
A type cast is basically a conversion from one type to
another. There are two types of type conversion:
1.
Implicit Type Conversion Also
known as ‘automatic type conversion’.
·
Done by the compiler on its own,
without any external trigger from the user.
·
Generally takes place when in an
expression more than one data type is present. In such condition type
conversion (type promotion) takes place to avoid lose of data.
·
All the data types of the variables
are upgraded to the data type of the variable with largest data type.
·
bool -> char ->
short int -> int ->
·
·
unsigned int -> long
-> unsigned ->
·
·
long long -> float
-> double -> long double
·
It is possible for implicit
conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
// An example of implicit conversion
#include <iostream>
using namespace std;
int main()
{
int
x = 10; // integer x
char
y = 'a'; // character c
// y
implicitly converted to int. ASCII
// value of 'a' is
97
x =
x + y;
// x
is implicitly converted to float
float
z = x + 1.0;
cout
<< "x = " << x << endl
<<
"y = " << y << endl
<<
"z = " << z << endl;
return
0;
}
Output:
x = 107
y = a
z = 108
Explicit Type
Conversion: This process is
also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type.
In C++, it can be done by two ways:
·
Converting by assignment: This is done by explicitly defining the required type
in front of the expression in parenthesis. This can be also considered as
forceful casting.
Syntax:
|
// C++ program to demonstrate // explicit type casting using namespace std; { double x = 1.2; int sum = (int)x + 1; } |
Conversion
using Cast operator: A Cast
operator is an unary operator which forces
one data type to be converted into another data type.
C++ supports four types of casting:
1. Static
Cast
2. Dynamic Cast
3. Const
Cast
Example:
Output: 3 |
Advantages
of Type Conversion:
·
This is done to take advantage of
certain features of type hierarchies or type representations.
·
It helps to compute expressions
containing variables of different data types.
static_cast in C++ | Type Casting operators
A Cast operator is an unary operator which
forces one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Static Cast: This is the simplest type of
cast which can be used. It is a compile
time cast.It does things like implicit conversions between
types (such as int to float, or pointer to void*), and it can also call
explicit conversion functions (or implicit ones).
Output: 3 |
Now let’s make a few changes in the code.
If you
compile the code, you will get an error: [Error] invalid static_cast from type 'char*' to type 'int*' This
means that even if you think you can some how typecast a particular object
int another but its illegal,
static_cast will not allow you to do this. |
Lets take another example of converting object to and from a class.
Run the above
code: Conversion Ctor called Conversion Operator Conversion Ctor called Conversion Operator Conversion Ctor called |
1. const_cast
const_cast is used to cast away the constness of
variables. Following are some interesting facts
about const_cast.
Type Conversion in C++
A type cast is basically a conversion from one type to another. There are two types of type conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the variable with largest data type.
• bool -> char -> short int -> int ->
•
• unsigned int -> long -> unsigned ->
•
• long long -> float -> double -> long double
• It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).
// An example of implicit conversion
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
Output:
x = 107
y = a
z = 108
=============================================================
Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
• Converting by assignment: This is done by explicitly defining the required type in front of the expression in parenthesis. This can be also considered as forceful casting.
Syntax:
// C++ program to demonstrate
// explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Conversion using Cast operator: A Cast operator is an unary operator which forces one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
===================================
The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.
============================================
Example:
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
// using cast operator
int b
• This is done to take advantage of certain features of type hierarchies or type representations.
• It helps to compute expressions containing variables of different data types.
= static_cast<int>(f);
cout << b;
}
Output:
3
Advantages of Type Conversion:
static_cast in C++ | Type Casting operators
A Cast operator is an unary operator which forces one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
int a = f; // this is how you do in C
int b = static_cast<int>(f);
cout << b;
}
Output:
3
Now let’s make a few changes in the code.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
char c = 'a';
// pass at compile time, may fail at run time
int* q = (int*)&c;
int* p = static_cast<int*>(&c);
return 0;
}
If you compile the code, you will get an error:
[Error] invalid static_cast from type 'char*' to type 'int*'
This means that even if you think you can some how typecast a particular object int another but its illegal, static_cast will not allow you to do this.
Lets take another example of converting object to and from a class.
#include <iostream>
#include <string>
using namespace std;
class Int {
int x;
public:
Int(int x_in = 0)
: x{ x_in }
{
cout << "Conversion Ctor called" << endl;
}
operator string()
{
cout << "Conversion Operator" << endl;
return to_string(x);
}
};
int main()
{
Int obj(3);
string str = obj;
obj = 20;
string str2 = static_cast<string>(obj);
obj = static_cast<Int>(30);
return 0;
}
Run the above code:
Conversion Ctor called
Conversion Operator
Conversion Ctor called
Conversion Operator
Conversion Ctor called
`.4
=======================================
////1. const_cast////
const_cast is used to cast away the constness of variables. Following are some interesting facts
about const_cast.
const_cast can be used to pass const data to a function that doesn’t receive const. For example, in the following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of const_cast.
============================
#include <iostream>
using namespace std;
int fun(int* ptr)
{
return (*ptr + 10);
}
int main(void)
{ const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
cout << fun(ptr1);
return 0;
}
===============================
/////////////////////////////////////////////////////////////////////////////////////////////////
https://www.educative.io/edpresso/what-is-dynamic-casting-in-cpp
----------------------------------------------------
. In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).
Dynamic casting checks consistency at runtime; hence, it is slower than static cast.
Take a look at the function signature of the dynamic cast below:
================================================================
///////////////////////////////////////////////////////////
reinterpret_cast is a type of casting operator used in C++.
It is used to convert one pointer of another pointer of any type, no matter either the class is related to each other or not.
It does not check if the pointer type and data pointed by the pointer is same or not.
===================
// CPP program to demonstrate working of
// reinterpret_cast
#include <iostream>
using namespace std;
int main()
{
int* p = new int(65);
char* ch = reinterpret_cast<char*>(p);
cout << *p << endl;
cout << *ch << endl;
cout << p << endl;
cout << ch << endl;
return 0;
}
=========================Output:
65
A
0x1609c20
A
----------------------------------
Comments
Post a Comment