What is meant by type conversion? Define two way of converting one user defined data type (object) to another user defined object? Write a program that converts object of another distance class with data members feet and inch.(Assume 1m = 3.3 feet and 1cm = 0.4 inch)

This answer is restricted. Please login to view the answer of this question.

Login Now

Type casting refers to changing an variable of one data type into another.

Type conversion can be classified into the following two types:

1.Implicit Type Conversion

When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.

#include <iostream>
using namespace std;

int main(){

    int x = 10; // integer x
    char y = 'a'; // character c

    // y implicitly converted to int. ASCII
    // value of 'a' is 97
    x = x + y;

    // x is implicitly converted to float
    float z = x + 1.0;

    cout << "x = " << x << endl
        << "y = " << y << endl
        << "z = " << z << endl;

    return 0;
}

2.Explicit Type Conversion

The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting.

Type casting in c is done in the following form:

(data_type)expression;

Example:

#include <iostream>
using namespace std;

int main(){
    double x = 1.2;
    // Explicit conversion from double to int
    int sum = (int)x + 1;
    cout << "Sum = " << sum;
    return 0;
}

Program Part:

#include<iostream>
using namespace std;

class Distance{

    public:
        int inch = 20;
        int feet = 15;

        void display(){
            cout << "Inch: " << inch << endl;
            cout << "Feet: " <<  feet << endl;
        }

};

class Distance_two{

    public:
        float meter;
        float cm;

        void operator = (Distance a){
            meter = (1 / 3.3) * a.feet;
            cm = (1 / 0.4) * a.inch;
        }

        void display(){
            cout << "Meter: " << meter << endl;
            cout << "Centimeter: " <<  cm << endl;
        }

};

int main(){

    Distance a;
    Distance_two b;

    //CLass type conversion with operator overloading
    b = a;

    //displaying data
    a.display();
    b.display();

    return 0;
}

The output of above program is:

Inch: 20
Feet: 15
Meter: 4.54545
Centimeter: 50
If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .