Skip to content
Related Articles

Related Articles

Conversion Operators in C++

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 20 Dec, 2021
View Discussion
Improve Article
Save Article

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.
For example consider the following class, here, we are making a class for complex numbers. It has two data members: real and imaginary. 

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;
}


Output

5
5

We are printing the magnitude of Complex objects in two different ways.
Note that 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 function (or making use of C++ Variant class) to perform such conversions. At some places, for example in making compatible calls with the existing C library, these are unavoidable.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!