Run Time Type Information (RTTI)
Run Time Type Information (RTTI):
- one of the powerful features of Delphi is that when it compiles an
application or a DLL, it stores information about each object's type &
its parent type in a code section called RTTI. This allows the program then
to determine at runtime an object's type (via use of the keyword "is")
and then determine whether certain properties or methods can be assigned to
it by checking its and its ancestor's properties & methods.
- This then allows you to assign a property or method to an object as if it
was of that object type or an ancestral object type using the Delphi keyword
- Why would you want to do this?
- let's say you have various data-aware controls on a form which point
to different datasets and when a user moves from one to another you wish
to ensure that a single DBNavigator points to the same dataset as the
- instead of writing code for every control, you can write it for
one control and assign that code to every other control as long as
it is written correctly such as:
- DBNavigator1.datasource := (Sender as
- as long as every control you assigned this method to had a
datasource property, this would work fine, but let's say you had a
button that displayed a grid and you wanted the navigator to point
to the grid's dataset before the user even hit the grid, then this
code could be extended so that it could be assigned to the button's
OnClick event as well without an error occurring:
- if Sender is TButton then //check RTTI to see
if the object that called this is a TButton
- DBNavigator1.datasource :=
- else DBNavigator1.datasource := (Sender as
- What is stored in the RTTI?
- the RTTI for an object contains quite a few sections:
- automation table
- init/finalization table
- typeinfo table
- Virtual Method Table (VMT):
- published field table
- published method table
- dynamic method table
- class name
- instance size
- pointer to its parent class
- TObject virtual methods
- user-defined virtual methods
- Delphi uses the parent class pointer to implement the is and as
operators, as well as the InheritsFrom method.
- Compiling a class reference as a pointer to the class' VMT, Delphi
compares VMT pointers to test whether one class is derived from another.
- The is operator compares an object's VMT pointer to the test class'
VMT. If they are not the same, Delphi follows the parent class pointers
until it finds a match, or runs out of parents (ie. gets to TObject
which has no parent). If a match is found in the ancestral tree then the
is operator returns true otherwise it returns false;
- This comparison does not work across modules such as when comparing a
class in an application to a class in a loaded DLL, because each module
has its own copy of the RTTI for its classes & Delphi can't do the
comparisons across the modules.The way to get around this is to build
any type checking & type casting required by your class into the
class itself (see DI Oct 1996).