Title: Type Conversions
1Type Conversions
- Lecture 14
- Wed, Feb 18, 2004
2Topics
- Constructors as type converters
- Conversion operators
3Conversion of Types
- Frequently in a program an object must be
converted from one type to another. - For the built-in types, this is done
automatically whenever it is sensible. - Convert float to int.
- Convert int to float.
- How can it be done with created types?
4Converting to a Created Type
- A class uses its constructors to define rules for
converting an object of another type to an object
of that type. - The prototype is
Class-nameClass-name(other type)
RationalRational(int) ComplexComplex(double)
5Example Convert int to Rational
// Rational constructor RationalRational(in
t n) numerator n
denominator 1 return // Usage
int i 100 Rational r r
(Rational)i r Rational(i)
6Converting to a Built-in Type
- Sometimes we want to convert an object of a
created type to an object of a built-in type. - For example, we might want to convert
- A Rational to a float.
- A Complex to a double.
- For this we need a conversion operator.
7Conversion Operators
- A conversion operator has prototype
Class-nameoperator built-in-type() const
- The operator converts the created-type object to
the built-in type and returns the object of the
built-in type.
Rationaloperator float() const Complexoperato
r double() const
8Example Convert Rational to float
Rationaloperator float() const return
(float)numerator/denominator