Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section8.2Point objects
As a simple example of a compound structure, consider the concept of a mathematical point. At one level, a point is two numbers (coordinates) that we treat collectively as a single object. In mathematical notation, points are often written in parentheses, with a comma separating the coordinates. For example, indicates the origin, and indicates the point units to the right and units up from the origin.
A natural way to represent a point in C++ is with two doubles. The question, then, is how to group these two values into a compound object, or structure. The answer is a struct definition:
This definition indicates that there are two elements in this structure, named x and y. These elements are called instance variables, for reasons I will explain a little later.
It is a common error to leave off the semi-colon at the end of a structure definition. It might seem odd to put a semi-colon after a squiggly-brace, but you’ll get used to it.
The first line is a conventional variable declaration: blank has type Point. The next two lines initialize the instance variables of the structure. The “dot notation” used here is similar to the syntax for invoking a function on an object, as in fruit.length(). Of course, one difference is that function names are always followed by an argument list, even if it is empty.
As usual, the name of the variable blank appears outside the box and its value appears inside the box. In this case, that value is a compound object with two named instance variables.