From the GoF book:
Prototype is particularly useful with static languages like C++, where classes are not objects, and little or no type information is available at run-time. It's less important in languages like Smalltalk or Objective C that provide what amounts to a prototype (i.e., a class object) for creating instances of each class. This pattern is built into prototype-based languages like Self [US87], in which all object creation happens by cloning a prototype.
What is meant by "classes are not objects"?
Isn't that always the case?
What does it mean for a class to be an object?
In some languages, when you declare a class, the language-runtime creates an object in memory to represent that class and its properties; you can then call methods on that class-object to find out properties of the class or create objects of that class, and so on.
C++ doesn't have that feature (largely because C++ is designed to minimize runtime overhead); there is no object representing the class. (The closest it comes to that is RTTI's type_info object, but that is really just an object containing some information about the class, and not a full representation of the class itself)
What is meant by "classes are not objects"?
Exactly what it sounds like. In some languages, classes themselves are also objects that you can send messages to. For example, in order to create an instance of a class (i.e. a new object), you send the +alloc
message to the class (and then you typically send the resulting object an -init
message:
Foo *newFoo = [[Foo alloc] init];
Isn't that always the case?
No. See above. See also Is class an object in object oriented language and Are classes objects in Objective-C?. Examples besides Objective-C include Smalltalk, Scheme, and Dylan.
What does it mean for a class to be an object?
It means that you can work with a class much as you would any other object. Details vary depending on the language. In Objective-C, a class is an object because it's an instance of the Class
meta-class. Objective-C makes a distinction between instance methods, i.e. the messages that can be sent to an instance of the class, and class methods, i.e. the messages that can be sent to the class itself. For example, it's very common to have a shared instance of a class and a class method that gets that shared object:
NSFileManager *fileManager = [NSFileManager defaultManager];
Notice that we're not actually allocating an object here, just asking the class for the shared instance (which the class manages) that may or may not already exist (if it doesn't, the class generally creates it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With