Mega Code Archive

 
Categories / Delphi / Strings
 

How does run-time type information [rtti] work

There are two new operators: "as" and "is." The "as" operator is a protected typecast. You can use it to force the compiler to treat an object of one type as another type, but if at run-time the typecast is not properly compatible, then you will get an error. For example, if you have a class called TSport, with descendants TBasketball and TFootball, you might want a variable of type TSport--but you might also happen to know at a certain point in the program that this variable actually contains an instance of a TFootball. So, you can refer to it as (MySport as TFootball) in order to get access to its football-specific properties. However, if you are wrong and somehow a TBasketball gets passed in, instead of just looking at the data in some oddball way like a regular typecast, this will generate an error. The "is" operator is used to compare an instance of an object to a class of objects, to see if a typecast using "as" will work. If you have a variable MySport of type TSport, and it currently contains an instance of a TBasketball, then the following statements are true: (MySport is TSport) (MySport is TBasketball) not (MySport is TFootball) The combination of these two operators might lead to code such as the following: function player_goodness(var MySport: TSport): integer; begin if (MySport is TBasketball) then player_goodness := (MySport as TBasketball).rebound_shots else if (MySport is TFootball) then player_goodness := (MySport as TFootball).total_yardage; end; It has been pointed out that this would be better implemented as a method which TSport defines and TBasketball and TFootball override, but then it wouldn't illustrate how RTTI works, would it? :-)