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 smart role in such situations.
For example consider the following class
We are printing the magnitude of Complex object in two different ways.
Note that usage of such smart (over smart ?) techniques are discouraged. 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 existing C library, these are unavoidable.
— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Advanced C++ | Virtual Constructor
- Advanced C++ | Virtual Copy Constructor
- Advanced C++ with boost library
- What is conversion constructor in C++?
- Catch block and type conversion in C++
- Conversion of Struct data type to Hex String and vice versa
- Conversion of whole String to uppercase or lowercase using STL in C++
- Type Conversion in C++
- What are the operators that can be and cannot be overloaded in C++?
- Increment (Decrement) operators require L-value Expression
- Order of operands for logical operators
- const_cast in C++ | Type Casting operators
- Bitwise Operators in C/C++
- How to sum two integers without using arithmetic operators in C/C++?
- Execution of printf with ++ operators
- Conditionally assign a value without using conditional and arithmetic operators
- new and delete operators in C++ for dynamic memory
- Overloading stream insertion (<>) operators in C++
- Operators in C / C++
- Unary operators in C/C++