Type Casting

Type Casting causes the program to treat a variable of one type as though it contains data of another type. Normally, this is used with a collection of pointers (addresses) to specify how to interpret the data. It is also used with polymorphism - where derived objects are treated as though they are actually base class objects.

When casting is not used with object pointers, it normally means to simply copy the data between incompatible types without converting the data or flagging an error. Bascially, this allows the programer to override the compiler's error checking.

Visual Basic | Delphi | C++ Builder | Windows API

Visual Basic 6.0

VB provides 11 type conversion functions, but type casting is not listed in the help file.
 i = CInt(f)  ' Converts f to an integer


In general, the original and new types must be the same size (ie occupy the same number of bytes in memory). However, when working with objects, it is common to cast a pointer to a derived object as though it referenced a smaller base object.

A straight cast is evaluated at compile time. When as is used with an object, additional code is generated to verify at run time that the new type is a base class of the referenced object.

 i := integer(f)   ; // Treats f as an integer
 i := f as integer ; // Fails with non-object types 

 with Sender as TButton do         // Parentheses are not required here
 with TButton (Sender) do
 (Sender as TButton).Caption := '&Ok'; // Parentheses are required here
     TButton(Sender).Caption := '&Ok'; // Parentheses are required here

C++ Builder

The cast operator actually performs the conversion even if the 2 types don't occupy the same number of bytes.
a = (char)i; // Treat i as a char and assign it to a

Windows API

Author: Robert Clemenzi - clemenzi@cpcug.org
URL: http:// cpcug.org / user / clemenzi / technical / Languages / TypeCasting.htm