C++ basic to class type
The conversion form basic type to class type is easy to accomplish. It may be recalled that the use of instructors was illustrated in a number of examples to initialize objects. For example, a constructor was used to build a vector object from an int data type array. Similarly, we used another constructor to build a string type object from a char* type variable. here are all examples where constructors perform a type conversion from the argument’s type to the constructor’s class type.
Consider the following constructor:
: : string( *a)
{
length = strlen(a);
p = new char[length+1];
strcpy(p,a);
}
|
This constructors builds a string type object from a char* type variable a as show in the above example. The variables length and p are data members of the string class. Once this constructor has been defined in the class string , It can be used for conversation from char* type to string type.
Example:
String s1,s2;
char? name1 = “IBM PC”;
char? name2 = “Apple Computers”;
s1 = string(name1);
s2 = name2;
|
The statement
S1 = string(name);
S2 = name2;
Also does the same job by invoking the constructor implicitly.
Let us take another example of converting an int data type to a class type.
time
{
hrs;
mins;
;
. . . .
. . . .
time( t)
{
hours = t/60;
mins = t%60;
}
};
|
The following conversion statements can be used in a function:
Time = T1;
duration = 85;
T1 = duration;
|
After this conversion, the hours member of T1 object will contain a value of 1 and mins member a value of 25, denoting 1 hours and 25 minutes.
Note ! The constructors are used for type conversion, take the single argument whose type is to be converted.
In both the examples, the left-hand side operand of = operator is always be a class object, Therefore, we can also accomplish this conversion using an
overloaded = operator.