Cast & RTTI
Introduction
RTTI stands for "Run Time Type Information", and it means that we are able, at runtime, to determine the exact type of an object. This is absolutely necessary if we wish to implement run time check exception like "ClassCastException" and for an another reason that I'm going to explain right now.
Imagine the following class/interface hierarchy :
class A
{
int myInt;
void test(){..};
}
interface B
{
void iTest();
}
class C : A, B
{
void test2(){..};
int truc;
}
To fully understand the problem, we need the diagramm of the memory representation of C :

Let me explain a few things. The first V-table contains adresses for both A & B, with function coming from A at the beginning, followed by the member variable of A.
Next, we have the second V-table, coming from the C interface and lastly, the members variable from C.
Suppose we have the following code :
C myC = new C();
B ab = cast(B) myC;
What Will happen ? Well, the compiler will add 8 to the C 'this' pointer
(that represents an 8 bytes displacement. 4 bytes coming from V-table and another 4 bytes from 'myInt') and stores the result into 'ab'.
'ab' now points at the V-Table from 'A', and this is exactly what we want.
The compiler is able to do this displacement because it is aware of the memory layout of C. But now, let's go a bit further :
Here we have serious problem. The compiler has no way to know that it musts subtract 8 byte from 'ab' in order to find again the right 'this' pointer.
(there is no binding between 'B' and 'A', but we should be able to do this conversion). And if we don't do this displacement, the generated code will be incorrect. (you may try this in C++ with C-Style cast, if you wish to see the results...).
This is why we need RTTI.
Kenaz implementation of RTTI
It starts like that :
1/ every class without superclass will have implicitely have the 'object' class as superclass
2/ any interface without superInterface will automatically have every functions defined in the 'object' class
(Java does exactly the same, for both points).
The 'object' class has one private member variable called 'type', describing the actual type of the object and a function 'getType' returning this variable.
This variable is automatically setted by the Kenaz run time when allocating a new object and point to a C++ object describing the type.
(Remember that Kenaz is embedded into C++ programs and that it can interact freely with C++ objects). When performing an implicit cast, the following operations will be performed :
- Push the wished type on the run-time stack<
- Call "GetType" from the source object and push the results on the the run-time stack
- Call a C++ function that will check if the cast is legal, and if yes,
- will use the information of both pushed type in order to find the displacement to apply. When the displacement is applied, the result is returned to the caller
top of page