Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of Objects and Primitives

Objects and Primitives

Java contains a small selection of primitive, or intrinsic, types. These are values that are not objects. This is one of the biggest semantic differences between Java and Smalltalk. In Smalltalk, primitive types are treated as objects and transparently boxed by the compiler or virtual machine. In Java and Objective-C, they are explicit.

Java only has a small selection of primitive types; four kinds of signed integer, two kinds of (signed) floating-point value, Booleans, and characters. Objective-C has all of the primitive types that C supports. The core set is similar, but with some important differences. The first is that C only defines the minimum range for a type. A short in Java is always 16 bits. A short in C is usually 16 bits. An int in Java is always 32 bits. An int in C is 16, 32, or 64 bits on platforms that exist today, may be 128 bits in the future, but is usually 32 bits on platforms where you'll use Objective-C.

Objective-C inherits the typedef keyword from C and a lot of standard definitions. The stdint.h header, for example, defines uint32_t and int32_t types, which are always unsigned or signed 32-bit integers on every platform that you might use.

One of the typedef'd types that Objective-C provides as standard is BOOL, which should only be YES or NO. This is really a char (an octet, on most platforms), and there are various ways in which it may get a value that is neither YES or NO.

Java and Objective-C share the same initialization rules for primitive types. If they are declared in an instance variable (what Java calls a field) in an object, then they will be initialized to 0 when the object is instantiated. If they are local variables, then they will be initialized to an undefined value.

Technically, Objective-C does not define how objects are instantiated. Unlike Java, Objective-C does not define a memory model at all; it inherits it from C. Objects are, by convention, allocated with something that wraps the C calloc() library function. On OS X, this wrapping is quite complex, but the end result is that every object you create will have uninitialized values set to 0.

One important difference is that Objective-C inherits all of the structured non-object types from C. In Java, everything is either an object or a primitive. In Objective-C, you also have structures, primitive arrays, and unions.

Cocoa uses a few structures in a number of places. These include things like NSPoint, which represents a point in 2D space. Unlike objects, which are always passed by reference, structures are commonly passed by value. They are also a lot cheaper to create than real objects.

  • + Share This
  • 🔖 Save To Your Account