Sometimes all the operations "stay within a type".
- Casting
- Traditionally, cast integers to floats, etc.
- May need to convert between user-defined types
- Cast operator (conversion operator)
- Convert from
- One class to another
- Class to built-in type (int, char, etc.)
- Must be non-static member function; Cannot be friend
- Do not specify return type; implicitly returns type to which you are converting
- Example
- Prototype
- A::operator char *() const;
- Casts class A to a temporary char *
- (char *)s calls s.operator char*()
- Also, overloaded cast-operator functions can be defined for converting objects of user-defined types into built-in types or into objects
of other user-defined types.
- A::operator int() const;
- A::operator OtherClass() const;
- Casting can prevent need for overloading
- Suppose class String can be cast to char *
- cout s; // s is a String
- Compiler implicitly converts s to char *
- Do not have to overload
2004-07-15