Conversion from class type data to basic type data in c++ (b/c) #19

For these types of conversions, we use casting operator function.

Casting operator function is a function whose syntax is defined as shown below-:

Class class_name

{

Private:

//data numbers

Public:

operator data_type() //casting operator function

{

//body of casting operator function

}

Characteristics of casting operator function-:

  1. It should be member of a class.
  2. It don’t take any argument.
  3. Return type is not specified.
  4. Although, the return type isn’t specified, it should have return statement.

The program is shown below.

 

First, understand and make it sure that you are going to convert class type to basic type.

And, I made it clear the you need a casting operator function.

Casting operator function is declared inside class (read point 1-it should be a member function of a class).

(See the code below just lightly scan through it and come back here again)

And, additionally inside the main function, make sure that you convert the required data by doing fer1=cel where cel is of class type .

Fer1 is of basic type.

Hence, in this way, a class type data can be converted into a basic type data.

the source code of this program is given as below.

 

Output-:

enter value in celsius

37

the equivalent temperature in fahrenheit is=

98.6

Note-: I am not giving output in form of pictures instead in text.

Do you like text output or not?

Assignment-:

 

Write a program to concatenate two strings using the concept  of binary operator overloading?(if you don’t know about operator overloading read the articles given at the bottom of the post)

 

HINT-:

1) make a string class….declare char name[30] inside it…make a default and parameterized constructor to take string as

strings(char *s)

{

name=s;

}

then call an operator overloading function as

strings operator +(strings st)

{

strings temp;

//copy name to temp.name

strcpy(temp.name,name);

//then concatenate using strcat…we can use strcat though we are asked to concatenate using operator overloading..

return temp;

}

then, display the name as-:

void display()

{

cout<<“name=”<<name;

}

 

next, inside the main function, initialize a string for constructor as:

strings s1(“my name”),s2(“xyz”),s3;

s3=s1+s2;

s3.display();

}

Try this code in your CodeBlocks. But, don’t copy and paste the code. I hope you can do this.

Learn Operator Overloading-:

#16-Operator overloading in C++-Unary and Binary operator overloading

Index operator overloading in C++-with program explanation also-easy to understand

#17-Relational Operator Overloading-Write a program to compare the magnitude of a complex number by overloading the <,>,==,!= operator.

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