Data Conversion in C++

06 Oct, 2021
A user-defined data types are designed by the user to suit their requirements, the compiler does not support automatic type conversions for such data types therefore, the user needs to design the conversion routines by themselves if required.
There can be 3 types of situations that may come in the data conversion between incompatible data types:
Conversion of primitive data type to user-defined type: To perform this conversion, the idea is to use the constructor to perform type conversion during the object creation. Below is the example to convert int to user-defined data type: 
Example:
C++
// C++ program to illustrate the// type-conversion#include <bits/stdc++.h>using namespace std; // Time Classclass Time {    int hour;    int mins; public:    // Default Constructor    Time()    {        hour = 0;        mins = 0;    }     // Parameterized Constructor    Time(int t)    {        hour = t / 60;        mins = t % 60;    }     // Function to print the value    // of class variables    void Display()    {        cout << "Time = " << hour             << " hrs and "             << mins << " mins\n";    }}; // Driver Codeint main(){    // Object of Time class    Time T1;    int dur = 95;     // Conversion of int type to    // class type    T1 = dur;    T1.Display();     return 0;}
Time = 1 hrs and 35 mins
Conversion of class object to primitive data type: In this conversion, the from type is a class object and the to type is primitive data type. The normal form of an overloaded casting operator function, also known as a conversion function. Below is the syntax for the same:
Syntax:
operator typename()
{
   // Code
}
Now, this function converts a user-defined data type to a primitive data type. For Example, the operator double() converts a class object to type double, the operator int() converts a class type object to type int, and so on. Below is the program to illustrate the same: 
Example:
C++
// C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std; // Tie Classclass Time {    int hrs, mins; public:    // Constructor    Time(int, int);     // Casting operator    operator int();     // Destructor    ~Time()    {        cout << "Destructor is called."             << endl;    }}; // Function that assigns value to the// member variable of the classTime::Time(int a, int b){    hrs = a;    mins = b;} // int() operator is used for Data// conversion of class to primitiveTime::operator int(){    cout << "Conversion of Class"         << " Type to Primitive Type"         << endl;     return (hrs * 60 + mins);} // Function performs type conversion// from the Time class type object// to int data typevoid TypeConversion(int hour, int mins){    int duration;     // Create Time Class  object    Time t(hour, mins);     // Conversion OR duration = (int)t    duration = t;    cout << "Total Minutes are "         << duration << endl;     // Conversion from Class type to    // Primitive type    cout << "2nd method operator"         << " overloading " << endl;     duration = t.operator int();     cout << "Total Minutes are "         << duration << endl;     return;} // Driver Codeint main(){    // Input value    int hour, mins;    hour = 2;    mins = 20;     // Function call to illustrate    // type conversion    TypeConversion(hour, mins);     return 0;}
Conversion of Class Type to Primitive Type
Total Minutes are 140
2nd method operator overloading 
Conversion of Class Type to Primitive Type
Total Minutes are 140
Destructor is called.
Conversion of Class Type to Primitive Type
Total Minutes are 140
2nd method operator overloading 
Conversion of Class Type to Primitive Type
Total Minutes are 140
Destructor is called.
 
Now, the function will convert the vector to scalar magnitude. The operator double() can be used as:  
double len = double(S1);
            Or,
double len = S1;
where S1 is an object of type vector.
Conversion of one class type to another class type: In this type, one class type is converted into another class type. It can be done  in 2 ways :
1.Using constructor
2.Using Overloading casting operator
1.Using constructor :
In the Destination  class we use the constructor method  
//Objects of different types 
ObjectX=ObjectY;
Here ObjectX is Destination object and ObjectY is source object
Example:
C++
#include<iostream>using namespace std;//cgs systemclass CGS {     int mts; //meters     int cms; //centimeters     public:       void showdata()   {       cout<<"Meters and centimeters in CGS system:";       std::cout << mts<<" meters "<<cms<<" centimeters" << std::endl;   }   CGS(int x,int y) // parameterized constructor   {       mts=x;    cms=y;   }    int getcms()   {       return cms;   }   int  getmts()   {       return mts;   }  };  class FPS {   int feet;   int inches;   public:   FPS() // default constructor   {       feet=0;       inches=0;   }    FPS(CGS d2)   {       int x;       x=d2.getcms()+d2.getmts()*100;       x=x/2.5;       feet=x/12;       inches=x%12;    }   void showdata()   {       cout<<"feet and inches in FPS system:";       std::cout << feet<<" feet "<<inches<<" inches" << std::endl;   } };  int main() {     CGS d1(9,10);     FPS d2;     d2=d1;     d1.showdata(); //to display CGS values     d2.showdata(); //to display FPS values     return 0; }
Meters and centimeters in CGS system:9 meters 10 centimeters
feet and inches in FPS system:30 feet 4 inches
2.Using Overloading casting operator 
// Objects of different types
objectX = objectY;
Here we use Overloading casting operator in source class i.e. overloading destination class in source class 
See the below example in which we have two classes Time and Minute respectively and will convert one class Time to another Minute class.
In the below example minute class is destination class and time class is source class
so we need to overload the destination class in the source class
Here we should not tell the return type but we returns the overloaded class object 
i.e. returning value without specifying return type 
C++
// C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std;//minutes classclass Minute {      public:   int mins;    // Constructors    Minute()    {        mins = 0;    }     // Function to print the value of    // hours and minutes    void show()    {        cout << "\nTotal Minute : " << mins << endl;    }}; // Time Classclass Time {    int hr, mins; public:    // Constructors    Time(int h, int m)    {        hr = h;        mins = m;    }    Time()    {        cout << "\nTime's Object Created";    }    operator Minute  () //overloading minute class    {        Minute m;        m.mins = (hr * 60) + mins;        return m;    } //driver code     // Function to print the value of    // hours and minutes    void show()    {        cout << "Hour: " << hr << endl;        cout << "Minute : " << mins << endl;    }}; // Minutes Classint main(){    Time T1(3,40);    Minute m;    m=T1; //minute class is destination and Time class is source class    T1.show();    m.show();    return 0;}
Hour: 3
Minute : 40

Total Minute : 220
tupakulateja3
varshagumber28
gulshankumarar231
C-Data Types
cpp-data-types
Articles
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++