
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- How do conversion operators work in C++?
- Type Conversion in Python
- Narrowing Conversion in Java
- Conversion constructor in C++?
- ZigZag Conversion in C++
- Conversion Functions in SQL
- Type Conversion in C++
- Conversion Disorder
- Energy Conversion
- Integral conversion characters in Java
- Data Type Conversion in Python
- Widening Primitive Conversion in Java
- Blob conversion function in Cassandra
- Bitwise Operators in C
- Division Operators in Python?

Advertisements