Declared in: <support/ClassInfo.h>
The class-information system is a set of macros that you use to discover information about an object's class, and cast an object to pose as an instance of some other class.
An object can supply three kinds of information about itself:
These three capabilities are embodied in the following macros,
const char *class_name(object) bool is_instance_of(object, class) bool is_kind_of(object, class)
where object is a pointer to any type of object and class is a class designator--it's not a string name (for example, you would use BView, not "BView").
The class_name() macro returns the name of the object's class. is_instance_of() returns TRUE if object is an instance of class, and FALSE otherwise. is_kind_of() returns TRUE if object is an instance of a class that inherits from class or an instance of class itself, and FALSE if not.
For example, given this slice of the inheritance hierarchy from the Interface Kit,
and code like this that creates an instance of the BButton class,
BButton *anObject = new BButton(...);
these three macros would work as follows:
const char *s = class_name(anObject);
if ( is_instance_of(anObject, BView) ) printf("The object is an instance of BView.\\n");
if ( is_kind_of(anObject, BView) ) printf("The object is a kind of BView.\\n");
Note that class names are not passed as strings.
An object whose class participates in the class-information system will permit itself to be cast to that class or to any class that it inherits from. The agent for this kind of "safe casting" is the following macro,
class *cast_as(object, class)
where object is an object pointer and class is a class designator.
cast_as() returns a pointer to object cast as a pointer to an object of class, provided that object is a kind of class--that is, provided that it's an instance of a class that inherits from class or is an instance of class itself. If not, object cannot be safely cast as pointer to class, so cast_as() returns NULL .
This macro is most useful when you have a pointer to a generic object and you want to treat it as a pointer to a more specific class.
Suppose, for example, that you retrieve a BWindow from a BView:
BWindow *window = myView->Window();
Furthermore, let's say that you suspect that the object that was returned is really an instance of a BWindow-derived class called MyWindow. If it is, you want to cast the object to be a MyWindow pointer. The cast_as() macro accomplishes this in one step:
MyWindow *mine; if ( mine = cast_as(window, MyWindow) ) /* mine is cast as a MyWindow object. */ else /* mine is set to NULL. */
The Be Book, HTML Edition, for Developer Release 8 of the Be Operating System.
Copyright © 1996 Be, Inc. All rights reserved.
Be, the Be logo, BeBox, BeOS, BeWare, and GeekPort are trademarks of Be, Inc.
Last modified September 6, 1996.