Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • C++ Classes and Objects
  • C++ Polymorphism
  • C++ Inheritance
  • C++ Abstraction
  • C++ Encapsulation
  • C++ OOPs Interview Questions
  • C++ OOPs MCQ
  • C++ Interview Questions
  • C++ Function Overloading
  • C++ Programs
  • C++ Preprocessor
  • C++ Templates
Open In App
Next Article:
Conversion Operators in C++
Next article icon

Conversion Operators in C++

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 an important role in such situations. It is similar to the operator overloading function in class.

In this article, we will learn how to implement conversion operators in our C++ program.

What are Conversion Operators?

Conversion operators are special member functions in a class that enable implicit or explicit conversion of objects of that class to another type. They help in situations where you need to convert an object of a user-defined type to a basic or another user-defined type.

Syntax

A conversion operator is declared using the operator keyword followed by the target type to which the object should be converted. Here’s the general syntax:

class ClassName { public:     operator TargetType() const; };

where,

  • TargetType is the type to which the conversion will take place.
  • const indicates that the conversion operator does not modify the object.

Example of Conversion Operator for a Class

Consider a simple example where we define a class Complex that represents complex numbers and provide a conversion operator to convert a Complex object to a double, representing the magnitude of the complex number. It has two data members:

  • real
  • imaginary
C++
// CPP Program to demonstrate Conversion Operators #include <cmath> #include <iostream> using namespace std;  class Complex { private:     double real;     double imag;  public:     // Default constructor     Complex(double r = 0.0, double i = 0.0): real(r)         , imag(i) {}      // magnitude : usual function style     double mag() { return getMag(); }      // magnitude : conversion operator     operator double() { return getMag(); }  private:     // class helper to get magnitude     double getMag()     {         return sqrt(real * real + imag * imag);     } };  int main() {     // a Complex object     Complex com(3.0, 4.0);      // print magnitude     cout << com.mag() << endl;     // same can be done like this     cout << com << endl; } 

Output
5 5

In this example, the Complex class has a conversion operator operator double() const, which calculates and returns the magnitude of the complex number. So, we are printing the magnitude of Complex objects in two different ways.

Note: If a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed.

Implicit vs Explicit Conversion

By default, conversion operators in C++ can be used implicitly, which means the compiler will automatically use them when needed.

However, this can sometimes lead to unexpected behaviour or ambiguities. To prevent implicit conversions, you can use the explicit keyword.

Example of Explicit Conversion

C++
#include <cmath> #include <iostream>  using namespace std;  class Complex { private:     double real;     double imag;  public:     // Default constructor     Complex(double r = 0.0, double i = 0.0): real(r)         , imag(i){ }      // magnitude : usual function style     double mag() { return getMag(); }      // magnitude : conversion operator     explicit operator double() { return getMag(); }  private:     // class helper to get magnitude     double getMag()     {         return sqrt(real * real + imag * imag);     } };  int main() {     Complex c(3.0, 4.0);     double magnitude = static_cast<double>(c);     cout << "Magnitude: " << magnitude << "\n";      return 0; } 

Output
Magnitude: 5 

Note: 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 functions (or making use of C++ Variant class) to perform such conversions. In some places, for example in making compatible calls with the existing C library, these are unavoidable.

Applications of Conversion Operators in C++

Conversion operators are particularly useful in the following scenarios:

  1. Mathematical Operations: Converting complex numbers to magnitudes or angles.
  2. String Conversions: Converting custom string-like classes to std::string.
  3. Interfacing with APIs: Converting user-defined types to types required by external libraries or APIs.



Next Article
Conversion Operators in C++

K

kartik
Improve
Article Tags :
  • C Language
  • C++
  • cpp-operator
  • cpp-operator-overloading
  • CPP-OOPs
Practice Tags :
  • CPP
  • cpp-operator

Similar Reads

    Casting Operators in C++
    The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
    5 min read
    Type Conversion in C++
    Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
    4 min read
    Number System Conversion in C
    Number system conversion is a fundamental concept in computer science and programming. It involves changing the representation of a number from one base to another, such as converting a decimal number to binary or a hexadecimal number to binary.In this article, we will create a console program in th
    8 min read
    Convert String to int in C++
    Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we c
    7 min read
    Naming Convention in C++
    Naming a file or a variable is the first and the very basic step that a programmer takes to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way to read the code. In C++, naming conventions are the set of rules for choosing the valid name for
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences