[fpc-pascal] Cast, inheritance, etc

Chad Berchek ad100 at vobarian.com
Thu Dec 6 05:22:02 CET 2012


This is an example of why it is usually wise to use the AS operator 
except in performance critical places. Using the parentheses notation is 
an unsafe cast; type checking does not occur at the time of the cast. 
This is especially dangerous because you run the risk of corrupting 
memory by writing to an address outside the block allocated for that 
object. Using the AS operator you will get an exception right away.

Instead of:

s := TBClass(c).GetInfoA;

you would write:

s := (c as TBClass).GetInfoA;

Personally I always use AS unless it is in a very performance critical 
area or I'm inside a block of code where I have already checked the 
type. For example people would usually not use the AS operator in an IF 
statement that checks the type:

if c is TBClass then
   s := TBClass(c).GetInfoA; // AS would be wasteful here

On 12/4/2012 1:03 PM, Marcos Douglas wrote:
> Hi,
>
> See the code below.
> My question is: Why the cast worked, considering the c variable is a
> TAClass instance, not a TBClass.




More information about the fpc-pascal mailing list