Open In App

Conversion Operators in C++

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • real
  • 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

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

Output
Magnitude: 5

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:

  1. Mathematical Operations: Converting complex numbers to magnitudes or angles.
  2. String Conversions: Converting custom string-like classes to std::string.
  3. Interfacing with APIs: Converting user-defined types to types required by external libraries or APIs.




Next Article

Similar Reads