C++ Builder Tutorials

C++ Builder: Type-casting

Typecasting is making a variable of one type act like another type.

For example, you might have a float that you need to use in a function that requires an integer.
Or you receive the object Sender in an event handler, but you don't know the type of the Sender.


Implicit conversion

Implicit conversions are automatically done when a variable is copied to a variable of a compatible type.
For example:

float A;
int B;
A = 2000;
B = A + 1;

Here, the variable A has been typecast from float to int. We didn't have to specify any explicit typecasting.
This is known as a "standard conversion". Standard conversions are for fundamental data types, and allow conversions between numerical types (float to int, int to float, double to int...), to or from bool, and some pointer conversions.


Explicit conversion

Many conversions require an explicit conversion. For example, you might have a float that you need to use in a function that requires an integer:

float A;
int B;
A = 1.234;
B = SomeFunction(int(A));


Dynamic cast

Dynamic cast is often used for objects of which the type is only known when the application is running.
For example, when you are dealing one by one with all the components that are on a form, like in:

for (i = 0; i < Form1->ComponentCount; i++) {
  // do something with Form1->Components[i]
}

What you can do with a Components[i] depends on its type, its class.
But you don't know its class yet: is it a TLabel, a TButton, a TPanel...?
Here, the dynamic cast comes to the rescue.

Basic syntax:

Object2 = dynamic_cast<T> (Object1)

where T is a class type.

If Object1 is not of class type T, this results in the value NULL.

Example: clear the caption of every TPanel:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int i;
  TPanel *Panel;
  for (i = 0; i << ComponentCount; i++) {
    Panel = dynamic_cast<TPanel*>(Components[i]);
    if (Panel != NULL)
      Panel->Caption = "";
  }
}