- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do conversion operators work in C++?
In this article, we will see what is the conversion operator in C++. C++ supports object-oriented design. So we can create classes of some real-world objects as concrete types.
Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator. This is created like operator overloading function in class.
In this example, we are taking a class for complex numbers. It has two arguments real and imaginary. When we assign the object of this class into some double type data, it will convert into its magnitude using conversion operator.
Example Code:
#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) //default constructor {} 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; }
Output
Magnitude using normal function: 11.6619 Magnitude using conversion operator: 11.6619
Advertisements