Types, objects, variables and pointers

The main C++ program entities are types and objects. As remarked in Sect. 2.2, types can be elementary or user-defined. Each type describes a category of different values, also called objects. In practice, a type is a record defining the size and memory layout of the objects of that type. Objects are values belonging to an existing type that reside in a well-defined memory area. Consider the two objects:
  float myFloat;
  int myInt;
The myFloat object is of type float. In most architectures, this occupies 4 bytes of RAM. myInt is an object of type int that also occupies 4 bytes. This means that both objects could be stored at the very same memory location; yet, the fact that their type is different makes it impossible to misinterpret myFloat as an integer or myInt as a float.

A variable is a symbol that is assigned a type and a memory area of the correct size. Although an object is usually attached to a variable, it need not be so: one could manually create an object in memory and then delete the variable without freeing the memory. The object still resides in memory but is not attached to any variable. A pointer is a particular type of variable, whose assigned memory contains an address pointing to another memory area where the actual object is kept. Since pointers allow user access to an arbitrary part of the memory, they wield an unlimited control over the machine. Use with care.

In Fig. 2, a new type class MyClass is first declared as consisting of a char and an int. An object myObject of type MyClass is defined, and its components myChar and myInt are assigned values `x' and 1 respectively. A pointer ptrObject of type MyClass* is then simultaneously declared and defined, and assigned the address where the object myObject is stored.

Figure 2: Types, objects, variables and pointers.
% latex2html id marker 5263
\includegraphics[width=14cm]{varptr.eps}

Leo Liberti 2008-01-12