Conversion Operators in C++


In this article we will see what is the conversion operator in C++. C++ supports object oriented design. So we can create classes of some real world objects as concrete types.

Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator. This is created like operator overloading function in class.

In this example we are taking a class for complex numbers. It has two arguments real and imaginary. When we assign the object of this class into some double type data, it will convert into its magnitude using conversion operator.

Example Code

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
class My_Complex {
   private:
      double real, imag;
   public:
      My_Complex(double re = 0.0, double img = 0.0) : real(re), imag(img) //default constructor{}
      double mag() {    //normal function to get magnitude
         return getMagnitude();
      }
      operator double () { //Conversion operator to gen magnitude
         return getMagnitude();
      }
   private:
      double getMagnitude() { //Find magnitude of complex object
         return sqrt(real * real + imag * imag);
      }
};
int main() {
   My_Complex complex(10.0, 6.0);
   cout << "Magnitude using normal function: " << complex.mag() << endl;
   cout << "Magnitude using conversion operator: " << complex << endl;
}

Output

Magnitude using normal function: 11.6619
Magnitude using conversion operator: 11.6619

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements