Data conversion in c++ (c/c)-Convert one class type to another class type using one argument parameterized constructor-easy

Conversion from one class type to another class type-:

This can be performed either by the help of 1 argument parameterized constructor

OR

By the help of a casting operator function.

Remember, I repeat that the conversion from one class type to another class type can be done by using the casting operator function or the 1 argument parameterized constructor.

If we choose one argument parameterized constructor, then it should lie in a destination class.

Else, if we choose casting operator function, then it should lie in source class.

Examples-:

An example program to convert object of type polar to object of type cartesian using the argument parameterized constructor.

How to do this program?

First of all, we are going to use one argument parameterized constructor for this case.

( But, of course, we can use casting operator function.

But, I will show that in next program.)

And, we should know that the 1 argument parameterized constructor should be in destination class.

We are going to write a program to convert polar to Cartesian.

So source=polar and destination=Cartesian.

So, 1 argument parameterized constructor must be in Cartesian class.

Inside that 1 argument parameterized constructor, we should send the value in polar that we want to convert.

That’s all.

Now, there will be many ways of giving that 1 argument in the parameterized constructor.

The method, that we used is shown in the given program.

(I am intentionally leaving space, as it will help to make things clear, and there is no waste of paper)

Source code-:

 

Output-:

the given polar is

radius=5.5angle=45.5

the equivalent cartesian is=

x=0.291877y=5.49225

Be the first to comment

Leave a Reply

Your email address will not be published.


*