Conversion Operators in C++
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:
r = 0.0,
i = 0.0)
(real * real + imag * imag);
Complex com(3.0, 4.0);
cout << com.mag() << endl;
cout << com << endl;
We are printing the magnitude of Complex objects in two different ways.
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.
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!