In some projects, you may need a pointer that can point to several different object types (GENERAL_LINK). When you arrive at an object via such a pointer, you usually want to know the type of that object. In C, our library provided the SELF_ID organization for this purpose.
Using a typeless pointer is not a good strategy in C++ and should generally be avoided except for special situations. If you want to detect the object type, the standard method is to derive all of the classes (or at least those that you want to detect) from the same base class, and use virtual functions. For example:
class Obj {
...
virtual char *Iam(void){return "Obj";}
};
class Automobil : public Obj {
...
virtual char *Iam(void){return "Automobil";}
};
class Airplane : Obj {
...
virtual char *Iam(void){return "Airplane";}
};
In tests test4d.c and test7a.c, the original SELF_ID organization has been replaced with this more elegant technique.
However, this method has a serious disadvantage. If you attempt to call function Iam() on an object which is not derived from class Obj, your program will crash. The technique is not useful for sorting out incorrect (garbage) objects from correct types.
Chap.11.15 describes how OrgC++ gives you access to internal type tables, normally hidden by the compiler. This information can be also used for a safer type detection. In order to make this simple for you, the TYPE organization provides function vfCheck(void *p) which, for a pointer to any memory location, can tell you whether the object is of the type registered with ZZ_EXT_.., and what the type is.
ZZ_HYPER_TYPE(type);
int tp; // type index
void *p;
...
tp=type.vfCheck(p);
Function vfCheck() provides a smart check, because it does not require the existence of the common root object, and it does not crash when inquiring about an unregistered object. I just returns -1 as the signal that the type does not match any registered type.
Function vfCheck() does not use virtual function, it compares internal vf pointers used by the compiler, and derives the type from their values.
In order to detect the type, the following conditions must be met:
When condition (1) is not met, vfCheck() returns -1 (no known type). When conditions (2) or (3) are not met, vfCheck() returns -2 (compiler not suitable for type detection). vfCheck() never crashes, even when given a pointer to a location which does not represent a valid object.
The probability of not detecting a correct type, or of detecting a wrong type is 0. The probability of not detecting an invalid type is very small n/(2**32), where n is the number of valid types.
For an example of vfCheck(), see test39a.
| Next Section 11.11 Time Stamp |