Conversion Operators in C++
Last Updated :
25 Jul, 2024
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class.
In this article, we will learn how to implement conversion operators in our C++ program.
What are Conversion Operators?
Conversion operators are special member functions in a class that enable implicit or explicit conversion of objects of that class to another type. They help in situations where you need to convert an object of a user-defined type to a basic or another user-defined type.
Syntax
A conversion operator is declared using the operator keyword followed by the target type to which the object should be converted. Here’s the general syntax:
class ClassName {
public:
operator TargetType() const;
};
where,
- TargetType is the type to which the conversion will take place.
- const indicates that the conversion operator does not modify the object.
Example of Conversion Operator for a Class
Consider a simple example where we define a class Complex that represents complex numbers and provide a conversion operator to convert a Complex object to a double, representing the magnitude of the complex number. It has two data members:
C++
// CPP Program to demonstrate Conversion Operators
#include <cmath>
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0): real(r)
, imag(i) {}
// magnitude : usual function style
double mag() { return getMag(); }
// magnitude : conversion operator
operator double() { return getMag(); }
private:
// class helper to get magnitude
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
int main()
{
// a Complex object
Complex com(3.0, 4.0);
// print magnitude
cout << com.mag() << endl;
// same can be done like this
cout << com << endl;
}
In this example, the Complex class has a conversion operator operator double() const, which calculates and returns the magnitude of the complex number. So, we are printing the magnitude of Complex objects in two different ways.
Note: If a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed.
Implicit vs Explicit Conversion
By default, conversion operators in C++ can be used implicitly, which means the compiler will automatically use them when needed.
However, this can sometimes lead to unexpected behaviour or ambiguities. To prevent implicit conversions, you can use the explicit
keyword.
Example of Explicit Conversion
C++
#include <cmath>
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0): real(r)
, imag(i){ }
// magnitude : usual function style
double mag() { return getMag(); }
// magnitude : conversion operator
explicit operator double() { return getMag(); }
private:
// class helper to get magnitude
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
int main()
{
Complex c(3.0, 4.0);
double magnitude = static_cast<double>(c);
cout << "Magnitude: " << magnitude << "\n";
return 0;
}
Note: The compiler will have more control in calling an appropriate function based on type, rather than what the programmer expects. It will be good practice to use other techniques like class/object-specific member functions (or making use of C++ Variant class) to perform such conversions. In some places, for example in making compatible calls with the existing C library, these are unavoidable.
Applications of Conversion Operators in C++
Conversion operators are particularly useful in the following scenarios:
- Mathematical Operations: Converting complex numbers to magnitudes or angles.
- String Conversions: Converting custom string-like classes to
std::string
. - Interfacing with APIs: Converting user-defined types to types required by external libraries or APIs.
Similar Reads
Casting Operators in C++
The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer). Let's take a look at an example: [G
5 min read
Type Conversion in C++
Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { // Two variables of
4 min read
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we c
8 min read
Assignment Operators in C++
In C++, the assignment operator forms the backbone of computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language i.e. assign some value to the variables in
6 min read
Bitwise Operators in C++
In C+, Bitwise Operators are the operators that are used to perform bit-level operations on the integers. While performing these operations, integers are considered as sequences of binary digits. These operators are useful for low-level programming, system programming, and optimizing performance. C+
6 min read
Converting Number to String in C++
In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at som
4 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class m
4 min read
Unary Operators In C++
In C++, unary operators are the type of operators that work on a single value (operand). They perform operations like changing a value's sign, incrementing or decrementing it by one, or obtaining its address. C++ has a total of 9 unary operators: Table of Content Increment Operator (++)Decrement Ope
6 min read
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the typ
3 min read