

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Conversion Operators 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
- Related Questions & Answers
- How do conversion operators work in C++?
- Conversion Functions in SQL
- Narrowing Conversion in Java
- Type Conversion in Python
- Conversion constructor in C++?
- Type Conversion in C++
- ZigZag Conversion in C++
- Integral conversion characters in Java
- Data Type Conversion in Python
- Widening Primitive Conversion in Java
- Decimal to Binary conversion
- Number to word conversion
- What is Type Conversion?
- What is Type conversion in C#?
- Floating-point conversion characters in Java
Advertisements