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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Operators in C | Set 2 (Relational and Logical Operators)
- C | Advanced Pointer | Question 2
- C | Advanced Pointer | Question 3
- C | Advanced Pointer | Question 4
- C | Advanced Pointer | Question 5
- C | Advanced Pointer | Question 7
- C | Advanced Pointer | Question 8
- C | Advanced Pointer | Question 9
- C | Advanced Pointer | Question 10
- Advanced C++ with boost library
- Advanced C++ | Virtual Constructor
- C | Advanced Pointer | Question 1
- Advanced C++ | Virtual Copy Constructor
- Operators in C | Set 1 (Arithmetic Operators)
- What is conversion constructor in C++?