In this article, we will talk about the usage of the conversion operators in C++.
What is the Conversion Operator in C++?
In C++, a conversion operator is a member function that allows the implicit conversion of a user-defined class to another type. It enables some type of conversion to take place automatically, which makes code shorter.
Syntax
The syntax of conversion operators in C++ is as follows:
// code for the conversion
}
In the above code:
- “var_type” denotes the desired data type for the conversion of the object.
- The operator’s body inside the curly braces contains the conversion logic, which converts an object that has the “var_type” data type.
Example: Use of Conversion Operators
To understand the usage of the conversion operators, first, we have added the required libraries known as “<cmath>”, “<iostream>”, and “std”. Then, created the “ComplexNum” class that has the “real” and “imag” private double data type members. Then, declare a public class member that contains the constructor having the defined parameters data type and initialize with default value “0.0” for each, which describes the real and imaginary components of a complex integer, respectively.
After that, for calculating the magnitude of a complex integer, the public class has one method the “operator double()” as a conversion operator. The “double()” method will convert a complex object into a double value that represents its magnitude:
#include <iostream>
using namespace std;
class ComplexNum {
private:
double real;
double imag;
public:
// constructor
ComplexNum(double r = 0.0, double i = 0.0): real(r), imag(i){}
//Calculate magnitude using conversion operator
operator double() { return getMag(); }
//Calculate the magnitude of a complex number
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
In the “main()” function, we have generated a complex object “comp” and passed “5.0” and “3.0” as the value of the “real” and “imag” components. Lastly, the magnitude of the complex number is printed using the “operator double()” function as the conversion operator:
{
ComplexNum comp(5.0, 3.0);
cout <<"Magnitude Using Conversion Operator: " <<comp << endl;
}
Output
Conclusion
In C++, the conversion operator can be used to create conversions among user-defined types or built-in types. It also allows objects to be implicitly changed to another type and specified as class member functions that return an object of the targeted type. This guide described the usage of the conversion operators in C++.