AppDividend
Latest Code Tutorials

Type Conversion in C++ Example | C++ Type Conversion

0

Type Conversion in C++ Example | C++ Type Conversion is today’s topic. Type conversion is the conversion of one type into another type in C++. Type conversion is done to make one variable of one type compatible with the other variable which of a different kind for a single operation. For example, we have one variable of integer type, and we want it to be of float type for an operation to work so we can typecast that integer variable into a float variable.

Type Conversion in C++

The process of converting one predefined type into another is called as type conversion. When the constants and variables of different types are mixed in the expression, they are converted to the same type.

When variables of one type are combined with the variables of another type, the type conversion will occur.

There are two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

#Implicit Type Conversion

When the compiler does the conversion on its own without the user intervention, it is called implicit type conversion. It is also called “automatic type conversion.”

For example, if we assign an integer value to a double variable the compiler on its own typecast the variable and change it to double. See the following code example.

int a = 20;

float b;

b = a; // implicit conversion

In the above example, the value of integer variable a is 20, and we are typecasting it in a float variable b implicitly. Doing typecasting in the correct order is very important as if we don’t do typecasting in the correct order, it may result in data loss, overflow, sign loss(while converting signed and unsigned variables).

Correct order for type casting is from low to higher datatype as listed below:

bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long  long int -> float -> double -> long double

All  data types of the variables are upgraded to the data type of the variable with largest data type.

Drawbacks of the implicit type conversion can be avoided by using explicit type conversion.

#Explicit Type Conversion

When we explicitly do type conversions with user intervention, it is called explicit type conversion.

We generally force explicit type conversion because it either not following the order of high order rule of implicit conversion or the conversion is not commonly occurring.

Explicit type conversion is user-defined.

Generic typecasting can be done in two ways.

#C like casting

 #Syntax

(type) expression

 Example:    

double  x = 100.2;
y = (int)x; 
cout << "Integer value of x="<<y; &nbsp; &nbsp; //Explicit type casting from double to int

#Functional casting

#Syntax

type(expression)

Example:  :    

double&nbsp; x = 100.2
y = int(x);
cout<<"Integer value of x="<<y; &nbsp; &nbsp; //Explicit type casting from double to int

Explicit casting can also be done with the help of cast operators.

#Examples for type conversion in C++

Example 1:  Write a program to show the mechanism of implicit type conversion by changing an integer value to float and use it in operation of adding two numbers.

See the following code example.

#include <iostream>
using namespace std;
class A
{
public:
  int a = 10;
  float c = 20.2;
  void add()
  {
    cout << "The value of addition after implicit type conversion = " << a + c;
  }
};
int main()
{
  A obj1;
  obj1.add();
  return (0);
}

See the following output.

Type Conversion in C++ Example

#Example 2

Write a program to show the mechanism of explicit type conversion by changing the double value to an integer and use that integer value to find the area of a square.

See the following cpp code.

#include <iostream>
using namespace std;
class A
{
public:
  double x = 5.2;
  int y;

  void squarearea()
  {
    y = (int)x; /*Explicit Type Casting*/
    cout << "The area of square after type conversion is = " << y * y;
  }
};
int main()
{
  A obj1;
  obj1.squarearea();
  return (0);
}

See the following output.

C++ Type Conversion Tutorial

#Conversion using Cast operator

A Cast operator is a unary operator that 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

The static casting can perform the conversions between pointers to the related classes, not only upcasts (from pointer-to-derived to the pointer-to-base), but also downcasts (from pointer-to-base to the pointer-to-derived).

No checks are performed during the runtime to guarantee that an object being converted is a full object of the destination type.

See the following code.

#include <iostream> 
using namespace std; 
int main() 
{ 
	float f = 21.5; 

	// using cast operator 
	int b = static_cast<int>(f); 

	cout << b; 
} 

See the following output.

21

#Dynamic Cast

The dynamic_cast can only be used with the pointers and references to classes (or with void*). Its purpose is to ensure that a result of the type conversion points to the valid, complete object of the destination pointer type.

It naturally includes pointer upcast (converting from pointer-to-derived to the pointer-to-base), in the same way as allowed as the implicit conversion.

But the dynamic_cast can also downcast (convert from pointer-to-base to the pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is the valid, complete object of the target type.

#Const Cast

The const_cast type of casting manipulates the constness of the object pointed by the pointer, either to be set or to be removed. For example, to pass the const pointer to the function that expects a non-const argument.

#Reinterpret_cast

The reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is the simple binary copy of a value from one pointer to the other.

All the pointer conversions are allowed: neither the content pointed, nor a pointer type itself is checked.

It can also cast the pointers to or from the integer types. The format in which the integer value represents a pointer is a platform-specific.

The only guarantee is that the pointer cast to the integer type large enough to fully contain it such as intptr_t, is guaranteed to be able to be cast back to the valid pointer.

#Advantages of Type Conversion

  1. It is done to take advantage of certain features of the type hierarchies or type representations.
  2. It helps to compute the expressions containing variables of different data types.

Finally, Type Conversion in C++ Example | C++ Type Conversion Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.