Data Type Conversion in C++: Basic and User Defined Data Types

Discussion in 'C++' started by usmanmalik, Jan 29, 2014.

  1. usmanmalik

    usmanmalik New Member

    Joined:
    Dec 28, 2013
    Messages:
    19
    Likes Received:
    14
    Trophy Points:
    0
    Today I am going to explain another very important C++ concept: ’The Data Type Conversion in C++’. C++ has wide variety of data types ranging from the basic or primitive data types to the user defined data types. In this article, we are going to explain that how we convert these data types to other.

    It is easier to convert same type of data from one to the other. For instance if we have two integer variables say
    Code:
    int num1, num2;
    The compiler will automatically convert them from one form to other if an equal’s sign is used between these two. For example
    Code:
    num1 = num2; 
    will be automatically compiled by the compiler and no explicit logic needs to be embedded in the code. This is the case with basic data types.

    Now, come towards the user defined data types or what we call objects. In our article on operator overloading we explained how we can assign two variables of one user defined data types to each other. For example if we had class class1, we could create two objects of class1 like
    Code:
    class1 obj1, ob2;
    obj1=obj2
    
    In that all the values from the variables of obj2 will be copied into the corresponding variables of obj1.
    In both of our examples we are storing values between variables of same data type. First we stored data from an integer to another integer and then we stored user defined objects of class1 to another object of class1.

    What if we want to store a float type data into an integer or an object of class1 into another object of class2 i.e. the data type of both of these objects will be different. Here we need to introduce some coding logic and this is what we are going to do in this article.

    Conversion between basic data types



    Conversion between basic data types is a straight forward process and is often done implicitly. For example if you write
    Code:
    Int num1;
    float num2 = 0.516;
    
    Now, you want to assign the value of float to num1, you can do
    Code:
    num1= num2;
    Compiler will not generate any error in this case though; num1 is of integer type whereas num2 is of float type. This is implicit conversion where compiler will run some internal routine to convert the float value to integer.

    However, we can also direct the compiler to convert the float type to integer. This is called explicit conversion of basic type data.

    In Example1, we have explained how compiler implicitly converts basic data types.

    Example1

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    void main(void) {
    	int num1;
    	float num2 = 5.615;
    	num1=num2;
    	cout<<num1;
    }
    
    If you compile and run the above code, the output will be 5. Here we have two variables, num1 of type integer and num2 of type float and we initialized float with value 5.615. Then we stored the value of float variable in integer variable. We simple assigned the value using equals sign. We did not provide any programming logic, rather the compiler automatically run the conversion routine and store the integer type value of float into integer variable. The output of Example1 is follows

    Output1

    [​IMG]

    In Example1, float was implicitly converted into integer; truncating the decimal part. However, for the purpose of readability, we can also explicitly specify the conversion between float and integer. Look at Example2.

    Example2

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    void main(void) {
    	int num1;
    	float num2 = 5.615;
    	num1=static_cast<int>(num2);
    	cout<<num1;
    }
    
    In Example2, we have explicitly converted float into integer using the statement
    Code:
    num1=static_cast<int>(num2);
    The above statement shows that num2 is being converted into integer type. If you want to convert it into any other type, you can simply replace <int> with the <type>, where type is the type of data into which you want the conversion to be done.

    Conversion between Basic Data Types and User Defined Data types



    Conversion between basic data types is extremely simple as we studied in the last section. However; conversion between user defined and basic data types entails explicit programming logic because compiler doesn’t know anything about the user defined data type. Therefore, we have write code to convert basic data types into user defined data types and vice versa.

    1. Conversion from basic to user defined data type

    Conversion from basic to user defined data type is best explained with the help of an example. The most famous example, employed to explain conversion between basic and user defined data type is that of meters to distance class; where meter is a float type basic data type and distance is a user defined class. Some programming logic is implemented in order to convert the float to user defined class. You will be amazed to know that we will be able to do something like
    Code:
    Distance = float;
    We will be storing float values in distance class and will display it. Have a look at Example3 for the sample code.

    Example3

    Code:
    #include <iostream>
    using namespace std;
    const float MeterToFloat=3.280833;
    class Distance {
    	int feets;
    	float inches;
    	public:
    	Distance()  //Distance Constructor {
    		feets=0;
    		inches=0.0;
    	}
    	Distance(float numofmeters)  //Single Parameter constructor {
    		float feetsinfloat= MeterToFloat * numofmeters;
    		feets=int(feetsinfloat);
    		inches=12*(feetsinfloat-feets);
    	}
    	void displaydist()  // Method to display converted values {
    		cout<<"Converted Value is: "<<feets<<"\' feets and "<<inches<<'\"'<<" inches.";
    	}
    };
    int main() {
    	cout <<"Float to distance conversion.\n********************************\n";
    	float meters;
    	cout<<"Enter values in meter:";
    	cin >>meters;
    	Distance distance = meters;
    	distance.displaydist();
    }
    
    First look at the Distance class. It has two member variables: integer type feets and float type inches. It has a no argument constructor which will initialize the values of feets and inches to 0 and 0.0 respectively.

    Next, it has a constructor that takes a float type variable as an argument. Inside this constructor we multiply the passed float type variable with 3.280833 which is stored in constant MeterToFloat variable which has been defined constant in the beginning of the program. We are multiplying the passed float parameter with this number because passed variable will contain meters. And one meter contains 3.280833. In our distance class we have distance in feet and inches, therefore we converted the float to feet. Then we truncated the decimal part of the feet using
    Code:
    feets=int(feetsinfloat);
    This is another way to explicitly convert basic types, simple add the data type followed by the value in round brackets.

    Now, feets contain value in integer. But we want the inches part as well to be stored in inches variable. Therefore we subtracted the feets which is integer part from the actual feetinfloat variable that contains the complete converted value in feet. We multiplied the result with 12 to get exact figure in inches because one foot contains 12 inches. This the logic that will convert our float variable that contain meters to Distance variable which contain feet and inches.

    Next, we have simply added a method which displays the converted feet and inches to the output screen.

    Now come inside the main method, real magic begins there. We have declared a variable of type float, named meters. We ask the user to enter the distance in meters. User will enter the distance and using the below statement.
    Code:
    Distance distance = meters;
    We will convert a float type basic variable to a user defined type class variable. This was not possible explicitly therefore we had to write code to achieve the desired functionality. Now, when users enter the distance in meters, it will give back the result in corresponding number of feet and inches. The output of Example3 is as follows.

    Output3

    [​IMG]

    This way we have successfully converted a basic data type into a user defined data type using an equal to operator. Following the same strategy, you can convert other basic data types into user defined data types.

    2. Conversion from user defined data type to basic data type

    At first, conversion from a user defined data type to basic data type seems simple, one would say, it’s the reverse of what we have done in the last section. But actually it is lot trickier. A whole new concept is involved in conversion from user defined to basic data type, which is known as the overloading casting operator.

    Overloaded Casting Operator

    Overloaded casting operator actually overloads the built in casting operator. For example, you can achieve different functionality from a float casting operator. Syntax of overloaded casting operator is simple.
    Code:
    operator type()
    {
         .
         .
         .
    }
    
    You can see that it is a sort of function with no return type and no arguments. The ‘operator’ is the keyword that has to be used followed by basic data type. For example If you want to overload the float operator. You will overload it like operator float() {}.

    There are three conditions that need to be satisfied for an overloaded casting operator.
    1. Overloaded casting operator does not have any return type.
    2. It cannot take any parameters or in other words no arguments can be passed to an overloaded casting operator.
    3. Finally, it has to be defined inside a class definition. The class definition will be the user defined data type that we want to convert into a basic type whose casting operator has been overloaded.
    When you define this overloaded casting operator in a class and when you equate the object of that class with the basic data type, this function will be automatically called on the object. This concept will be explained by Example4. In Example4, we will do reverse of Example3, we will ask the user to enter the distance in feet and inches and then will convert the feet and inches into a variable of type float named meters. Have a look at Example4.

    Example4

    Code:
    #include <iostream>
    using namespace std;
    const float MeterToFloat=3.280833;
    // Meter to feet
    class Distance {
    	int feet;
    	float inches;
    	public:
    	Distance()          // Default Constructor {
    		feet=0;
    		inches=0.0;
    	}
    	Distance(int ft, float in)  //two arguements constructor {
    		feet=ft;
    		inches=in;
    	}
    	operator float()    //overloaded casting operator {
    		float feetinfractions=inches/12;
    		feetinfractions+=float(feet);
    		return (feetinfractions/MeterToFloat);
    	}
    };
    int main() {
    	int feet;
    	float inches;
    	cout <<"Enter distance in Feet and Inches.";
    	cout<<"\nFeet:";
    	cin>>feet;
    	cout<<"Inches:";
    	cin>>inches;
    	Distance dist(feet, inches);
    	float meters=dist;
    	// This will call overloaded casting operator
    	cout<<"Converted Distance in Meters is: "<< meters;
    }
    
    Look at the class definition. It is similar to example3 with one exception. It now contains an overloaded casting operator which overloads float type basic data type. Inside this operator definition, we have written logic to merge feet and inches to get a consolidate value in meters.
    float feetinfractions=inches/12;

    The above line converts the inches into feet. In the next line we have casted the feet member variable to float so that it can be added to feetinfractions. Now feetinfractions contain feet + the number of inches. We divided this value by MeterToFeet variable which contains value 3.280833. Then we have returned the result.

    Now, come inside the main function. Here we have again declared two variables: feet of type int and inches of type float. We then asked the user to enter the distance in feet and inches and then we have stored these values in the two variables defined earlier. We then passed these values to the Distance class variable. Two argument constructor of the distance class variable will be called and values will be stored in corresponding feet and inches member of Distance class. The real magic begins after that. Consider the following line of code.
    Code:
    float meters=dist;
    Here dist is the object of user defined distance class whereas ‘meters’ is the basic data type. We are equating a user defined data type to a basic data type. When compiler reaches this line, it will look that if an overloaded casting operator is available in the Distance class, which overloads the float operator. If such an operator is found, it will be called and executed. As, we have returned meters from the overloaded casting operator, that returned value will be stored in meters. This way we have successfully converted a user defined data type to a basic data type. Enter the reverse values as you entered in case of Example3 and you will see the result. The output of Example4 is as follows.

    Output4

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice