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++
#include <bits/stdc++.h>
using namespace std;
class Time {
int hour;
int mins;
public :
Time()
{
hour = 0;
mins = 0;
}
Time( int t)
{
hour = t / 60;
mins = t % 60;
}
void Display()
{
cout << "Time = " << hour
<< " hrs and "
<< mins << " mins\n" ;
}
};
int main()
{
Time T1;
int dur = 95;
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++
#include <bits/stdc++.h>
using namespace std;
class Time {
int hrs, mins;
public :
Time( int , int );
operator int ();
~Time()
{
cout << "Destructor is called."
<< endl;
}
};
Time::Time( int a, int b)
{
hrs = a;
mins = b;
}
Time::operator int ()
{
cout << "Conversion of Class"
<< " Type to Primitive Type"
<< endl;
return (hrs * 60 + mins);
}
void TypeConversion( int hour, int mins)
{
int duration;
Time t(hour, mins);
duration = t;
cout << "Total Minutes are "
<< duration << endl;
cout << "2nd method operator"
<< " overloading " << endl;
duration = t.operator int ();
cout << "Total Minutes are "
<< duration << endl;
return ;
}
int main()
{
int hour, mins;
hour = 2;
mins = 20;
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;
class CGS
{
int mts;
int cms;
public :
void showdata()
{
cout<< "Meters and centimeters in CGS system:" ;
std::cout << mts<< " meters " <<cms<< " centimeters" << std::endl;
}
CGS( int x, int y)
{
mts=x;
cms=y;
}
int getcms()
{
return cms;
}
int getmts()
{
return mts;
}
};
class FPS
{
int feet;
int inches;
public :
FPS()
{
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();
d2.showdata();
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++
#include <bits/stdc++.h>
using namespace std;
class Minute {
public :
int mins;
Minute()
{
mins = 0;
}
void show()
{
cout << "\nTotal Minute : " << mins << endl;
}
};
class Time {
int hr, mins;
public :
Time( int h, int m)
{
hr = h;
mins = m;
}
Time()
{
cout << "\nTime's Object Created" ;
}
operator Minute ()
{
Minute m;
m.mins = (hr * 60) + mins;
return m;
}
void show()
{
cout << "Hour: " << hr << endl;
cout << "Minute : " << mins << endl;
}
};
int main()
{
Time T1(3,40);
Minute m;
m=T1;
T1.show();
m.show();
return 0;
}
|
Output
Hour: 3
Minute : 40
Total Minute : 220
Similar Reads
C++ Program For String to Double Conversion
There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++. Methods to Convert String to Double We can convert String to Double in C++ using the following methods: Using stod() Fun
3 min read
C++ Serial Port Connection
In C++, interacting with hardware devices often involves serial port communication. This serial port communication is used for the transfer of data between a computer or a device and external peripherals like printers, scanners, and modems among others. In serial port programming, data is send in a
6 min read
Convert Float to String In C++
In this article, we learn how we can convert float to string in C++ using different methods: Using the to_string()Using stringstreamUsing MacrosUsing lexical_cast from the boost library1. Using to_string() The to_string() method takes a single integer variable or other data type and converts it into
3 min read
C++ Program For int to char Conversion
In this article, we will learn how to convert int to char in C++. For this conversion, there are 5 ways as follows: Using typecasting.Using static_cast.Using sprintf().Using to_string() and c_str().Using stringstream. Let's start by discussing each of these methods in detail. Examples: Input: N = 65
6 min read
std::fstream::close() in C++
Files play an important role in programming. It allows storage of data permanently. The C++ language provides a mechanism to store the output of a program in a file and browse from a file on the disk. This mechanism is termed file handling. In order to perform file handling, some general functions w
4 min read
Important functions of STL Components in C++
C/C++ Code // C++ code #include <iostream> #include <utility> using namespace std; int main() { // Declaring the PAIR1 of int and char // IF pair is not initialized then , // default value of int/double is 0 and // for string/char it is NULL pair<int, char> PAIR1; cout << PAI
15+ min read
Managing Console I/O operations in C++
Every program takes some data as input and generates processed data as an output following the familiar input process output cycle. It is essential to know how to provide the input data and present the results in the desired form. The use of the cin and cout is already known with the operator >
4 min read
Helper Function in C++ Classes
In C++, the users can keep their class methods organized and readable with the help of private helper functions. Helper functions are utility functions that are only accessible within the class. They can't be called externally but can be used by the class's public methods to perform lower-level task
3 min read
Swap Two Numbers using Function in C++
Swapping numbers means exchanging the values of the two numbers with each other. For Example, Before Swapping:a = 10, b = 22;After swapping:a = 22, b = 10In this article, we will write a program to swap two numbers using a function in C++. How to Swap Two Numbers Using Function in C++?We will pass t
3 min read
Convert Hex String to Signed Integer in C++
This article discusses converting a hex string to a signed integer in C++. There are 5 ways to do this in C++: Using stoi() function.Using stoul() function.Using sscanf() function.Using stringstream method.Using boost:lexical_cast.1. Using stoi function stoi is a function in the string header file.
6 min read