OOC:en:6.3 Roots — Object and Class

来自 ChinaUnix Wiki

Class descriptions with the same set of methods are the objects of a metaclass. A metaclass as such is a class and, therefore, has a class description. We must assume that the class descriptions for metaclasses once again are objects of meta (metameta?) classes, which in turn are classes and ...

It seems unwise to continue this train of thought. Instead, let us start with the most trivial objects imaginable. We define a class Object with the ability to create, destroy, compare, and display objects.

Interface Object.h:

   extern const void * Object; /* new(Object); */
   
   void * new (const void * class, ...);
   void delete (void * self);
   
   int differ (const void * self, const void * b);
   int puto (const void * self, FILE * fp);

Representation Object.r:

   struct Object {
       const struct Class * class; /* object’s description */
   };

Next we define the representation for the class description for objects, i.e., the structure to which the component .class in struct Object for our trivial objects points. Both structures are needed in the same places, so we add to Object.h:

   extern const void * Class; /* new(Class, "name", super, size,sel, meth, ... 0); */

and to Object.r:

   struct Class {
       const struct Object _; /* class’ description */
       const char * name; /* class’ name */
       const struct Class * super; /* class’ super class */
       size_t size; /* class’ object’s size */
       void * (* ctor) (void * self, va_list * app);
       void * (* dtor) (void * self);
       int (* differ) (const void * self, const void * b);
       int (* puto) (const void * self, FILE * fp);
   };

struct Class is the representation of each element of the first metaclass Class. This metaclass is a class; therefore, its elements point to a class description. Point¬ing to a class description is exactly what an Object can do, i.e., struct Class extends struct Object, i.e., Class is a subclass of Object!

This does not cause grief: objects, i.e., instances of the class Object, can be created, destroyed, compared, and displayed. We have decided that we want to create class descriptions, and we can write a destructor that silently prevents that a class description is destroyed. It may be quite useful to be able to compare and display class descriptions. However, this means that the metaclass Class has the same set of methods, and therefore the same type of description, as the class Object, i.e., the chain from objects to their class description and from there to the description of the class description ends right there. Properly initialized, we end up with the following picture:

图片:Ch6 3.jpg

The question mark indicates one rather arbitrary decision: does Object have a superclass or not? It makes no real difference, but for the sake of uniformity we define Object to be its own superclass, i.e., the question mark in the picture is replaced by a pointer to Object itself.

个主工具