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

Conversion from one class type to basic type-:

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

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.

But before writing it, we will learn how to write that program.

First, understand 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).

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?

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 overloader 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.

Be the first to comment

Leave a Reply

Your email address will not be published.


*