Data Conversion in C++-(c/c)-Converting a class type to another class type using casting operator function

In the last tutorial, we had changed from class A to class B type using the one argument parameterized constructor.

Now, in this tutorial, we are going to do the same thing using the casting operator function.

How to write this  program?

Before writing the code, it is necessary to remember that if we want to use casting operator function, then the simple rule is that it should lie in source class.

Let’s take a programming problem.

(Q) Convert an object of type ‘polar’ to object of type ‘cartesian’.

Here, source=polar


Since, the casting operator function needs to lie in source class, let’s start from source class=polar class.

inside polar class, we will have to include a casting operator function as follows-:

//operator to_what();

operator cartesian();

We are going to write the source class first, so we should be declaring class cartesian at the beginning (before class) to let the compiler know that cartesian class exists because we are using ….operator cartesian()..and if there is no such operator cartesian, the compiler would generate error.

and we will define the cartesian class after writing the cartesian class. (note that cartesian should be inside source class=polar class…that’s the reason behind polar::operator cartesian)

and we will need to take the value in polar, so we will take inputs in polar.

and we will have to display the equivalent cartesian (so use a display function in cartesian)

Source code:

Leave a Comment

Your email address will not be published. Required fields are marked *

Do NOT follow this link or you will be banned from the site! Scroll to Top