Skip to content
Related Articles

Related Articles

Data Conversion in C++
  • Difficulty Level : Medium
  • Last Updated : 15 Apr, 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 Class
class 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 Code
int main()
{
    // Object of Time class
    Time T1;
    int dur = 95;
 
    // Conversion of int type to
    // class type
    T1 = dur;
    T1.Display();
 
    return 0;
}
Output
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 Class
class 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 class
Time::Time(int a, int b)
{
    hrs = a;
    mins = b;
}
 
// int() operator is used for Data
// conversion of class to primitive
Time::operator int()
{
    cout << "Conversion of Class"
         << " Type to Primitive Type"
         << endl;
 
    return (hrs * 60 + mins);
}
 
// Function perfomrs type conversion
// from the Time class type object
// to int data type
void 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 Code
int main()
{
    // Input value
    int hour, mins;
    hour = 2;
    mins = 20;
 
    // Function call to illustrate
    // type conversion
    TypeConversion(hour, mins);
 
    return 0;
}
Output
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.

 

Output: 
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 system
class 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;
 }
Output
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 class
class 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 Class
class 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 Class
int main()
{
    Time T1(3,40);
    Minute m;
    m=T1; //mintue class is destination and Time class is source class
    T1.show();
    m.show();
    return 0;
}
Output
Hour: 3
Minute : 40

Total Minute : 220

 

 

 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :