Type Conversion in C++

C++ provides mechanism to perform automatic type conversion if all variable are of basic type. For user defined data type, programmers have to convert it by using constructor or by using casting operator.

The type of data to the right of an assignment operator is automatically converted to the data type of variable on the left. Consider the following example:

int x;
float y = 20.123;
x=y ;

This converts float variable y to an integer before its value assigned to x.

The type conversion is automatic as far as data types involved are built in types. We can also use the assignment operator in case of objects to copy values of all data members of right hand object to the object on left hand. The objects in this case are of same data type. But of objects are of different data types we must apply conversion rules for assignment.

Three type of situation arise in user defined data type conversion.

  1. Basic type to Class type
  2. Class type to Basic type
  3. Class type to Class type

1. Basic type to Class type

A constructor was used to build a matrix object from an int type array. Similarly, we used another constructor to build a string type object from a char* type variable. In these examples constructors performed a de-facto type conversion from the argument’s type to the constructor’s class type.

Consider the following constructor:

string :: string (char*a)
{
	length = strlen (a);
	name=new char[len+1];
	strcpy (name,a);
}

This constructor builds a string type object from a char* type variable a. The variables length and name are data members of the class string. Once you define the constructor in the class string, it can be used for conversion from char* type to string type.

Example

string si , s2;
char* namel = “Good Morning”;
char* name2 = “ STUDENTS” ;
s1 = string(namel);
s2 = name2;

The program statement si = string (namel); first converts name 1 from char* type to string type and then assigns the string type values to the object s1.

The statement s2 = name2; performs the same job by invoking the constructor implicitly.

Consider the following example:

class time
{
		int hours;
		int minutes;
	public:
		time (int t) // constructor
		{
			hours = t / 60; //t is inputted in minutes
			minutes = t % 60;
		}
};

In the following conversion statements :

time T1; //object Tl created 
int period = 160;
T1 = period; //int to class type

The object T1 is created. The variable period of data type integer is converted into class type time by invoking the constructor. After this conversion, the data member hours of T1 will have value 2 arid minutes will have a value of 40 denoting 2 hours and 40 minutes.

In both the examples, the left-hand operand of = operator is always a class object. Hence, we can also accomplish this conversion using an overloaded = operator.

2. Class type to Basic Type

The constructor functions do not support conversion from a class to basic type. C++ allows us to define a overloaded casting operator that convert a class type data to basic type. The general form of an overloaded casting operator function, also referred to as a conversion function, is:

Syntax:

operator typename( )
{
          //Program statement.
}

This function converts a class type data to typename data.

For example, the operator double( ) converts a class object to type double, in the following conversion function:

vector:: operator double ( )
{
	double sum = 0 ;
	for(int i = 0; i<size; i++)
		sum = sum + v[i] * v[i] ; //scalar magnitude
	return sqrt(sum);
}

The casting operator should satisfy the following conditions.

  1. It must be a class member.
  2. It must not specify a return type.
  3. It must not have any arguments. Since it is a member function, it is invoked by the object and therefore, the values used for, Conversion inside the function belongs to the object that invoked the function. As a result function does not need an argument.

In the string example discussed earlier, we can convert the object string to char* as follows:

string :: operator char*( )
{
      return (str) ;
}

3.One Class type to Another Class type

We have just seen data conversion techniques from a basic to class type and a class to basic type. But sometimes we would like to convert one class data type to another class type.

Example

Obj1 = Obj2;   //Obj1 and Obj2 are objects of different classes.

Obj1 is an object of class one and Obj2 is an object of class two. The class two type data is converted to class one type data and the converted value is assigned to the Obj1. Since the conversion takes place from class two to class one, two is known as the source and one is known as the destination class.

Such conversion between objects of different classes can be carried out by either a constructor or a conversion function. Which form to use, depends upon where we want the type-conversion function to be located, whether in the source class or in the destination class.

We studied that the casting operator function Operator typename( ) Converts the class object of which it is a member to typename. The type name may be a built-in type or a user defined one (another class type).

In the case of conversions between objects, typename refers to the destination class. Therefore, when a class needs to be converted, a casting operator function can be used. The conversion takes place in the source class and the result is given to the destination class object.

ConversionSource classDestination class
Basic to classNot applicableConstructor
Class to BasicCasting operatorNot applicable
Class to classCasting operatorConstructor
Conversion takes place in

Consider the following example of an inventory of products in a store. One way of keeping record of the details of the products is to record their code number, total items in the stock and the cost of each item.

Alternatively we could just specify the item code and the value of the item in the stock. The following program uses classes and shows how to convert data of one type to another.

#include<iostream.h>
#include<conio.h>
class stock2;
class stock1
{
		int code, item;
		float price;
	public:
	stock1(int a, int b, float c)
	{
		code=a;
		item=b;
		price=c;
	}
	void disp( )
	{
		cout<<”code”<<code <<”\n”;
		cout<<”Items”<<item <<”\n”;
		cout<<”Price per item Rs . “<<price <<”\n”;
	}
	int getcode( )
		{return code; }
	int getitem( )
		{return item; }
	int getprice( )
		{return price;}
	operator float( )
	{
		return ( item*price );
	}
};

class stock2
{
		int code;
		float val;
	public:
	stock2()
	{
		code=0; val=0;
	}
	stock2(int x, float y)
	{
		code=x; val=y;
	}
	void disp( )
	{
		cout<< “code”<<code << “\n”;
		cout<< “Total Value Rs . “ <<val <<”\n”
	}
	stock2(stockl p)
	{
		code=p.getcode ( ) ;
		val=p.getitem( ) * p.getprice( ) ;
	}
};

void main ( )
{
	Stockl il(101, 10,125.0);
	Stock2 i2;
	float tot_val;
	tot_val=i1 ;
	
	i2=il ;
	cout<<” Stock Details-stockl-type” <<”\n”;
	
	i1.disp ( ) ;
	cout<<” Stock value”<<”\n”;
	cout<< tot_val<<”\n”;
	
	cout<<” Stock Details-stock2-type”<< “\n”;
	
	i2 .disp( ) ;
	getch ( ) ;
}

You should get the following output.

Stock Details-stock1-type
code 101
Items 10

Price per item Rs. 125
Stock value
1250 

Stock Details-stock2-type 
code 101 
Total Value Rs. 1250

Related posts