In C++ expressions, the user-defined and built-in types are applied together. The compiler has no idea about user-defined data types and conversion to other data types. To overcome this problem, the programmer must design the procedures that convert basic data types to user-defined data types and vice versa.
There are three possibilities.
·
Conversion from Basic
to class type
·
Conversion from Class
to Basic Type
·
Conversion from one
class Type to another Class Type
1. Conversion from Basic to Class type
In C++, a variable of basic data
type will be converted into a data member of a class.
A Constructor is used for
conversion.
Example:
String(char *s)
{
Strcpy(str,s);
}
We invoke the constructor
String s1= “Hello!”;
(or)
String s1(“Hello!”);
Here string object is built from
the basic data type of char.
2. Conversion from Class type to Basic Data Type
In C++, A user-defined data type can
also be converted into a basic data type.
Overloaded casting operator is used
for conversion.
The syntax for an overloaded
operator is:
Operator type_name()
{
-------
}
Note:
·
The function does not
have any return type
·
The function converts
the class type into the type_name
·
The function does not
take any arguments.
3. Conversion from class to class type
In C++, an object of one class is
converted into that of another class.
Syn:- obj_dest = obj_source;
This conversion can be implemented
in two ways
·
Using a constructor
(Conversion in destination class)
Conversion in the source class
When performing conversion in the
source class, a type cast operator is used.
Syntax:-
operator typename()
{
--------
}
Operator is the keyword, typename
refers the destination type.
Conversion in destination class
When performing conversion in the
destination class, a single argument constructor is used where argument is the
object of the source class.
Syntax:-
class1( class2 obj)
{
--------
}
};
0 comments:
Post a Comment