C++ Conversion Operators Guide



What is Conversion Operator

Conversion operators are a type of operator overloading in C++. These operators are commonly known as type-cast operators. They enable a class or structure to specify how an object should be converted into another data type.

Sometimes we need to convert concrete-type objects to some other type of objects or primitive data types. To make this conversion we can use a conversion operator.

Following is the syntax to use the conversion:

class ClassName {
public:
   operator TargetType() const {
      // conversion logic
   }
};

Purpose of Using Conversion Operators

Following is the purpose of using the conversion Operators ?

  • We can convert class objects to built-in types (e.g., int, double, string)
  • we can convert class objects to user-defined types
  • It enables implicit or explicit casing

Example of Converting Object to Int

In the following example, we convert an object into an int:

#include <iostream>
using namespace std;

class Distance {
   int meters;
   public: Distance(int m) : meters(m) {}
      // Conversion operator to int
      operator int() const {
         return meters;
    }
};

int main() {
   Distance d(100);
   int m = d;
   cout << "Meters: " << m << endl;
   return 0;
}

The following is the output of the above code:

Meters: 100

Example of Converting Complex Number to Double

In this example, we create a class for complex numbers. It has two arguments real, and imaginary. We use the conversion operator to allow an object of the My_Complex class to behave like a double, returning its magnitude automatically:

#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){}
   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;
}

The above code generates following output:

Magnitude using normal function: 11.6619
Magnitude using conversion operator: 11.6619
Updated on: 2025-06-18T18:35:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started