Structures (Chapter 5) and classes (Chapter 9) are structured data types. Programs create objects from structures and classes, and those objects have an internal structure made up of smaller data units. Think of an object as a basket and the smaller data units as the contents of the basket. The data units are called fields or members. Programs access the individual members in an object with member selection operators. The text covers member selection in greater detail in the next chapter but introduces it here to explore all the pointer operators in one chapter. Given the similarity between C++ and Java classes, your previous experience Java experience is sufficient for you to understand this initial introduction.
The internal units in a Java class are called instance fields or instance variables and are the data for which an object has responsibility. Java classes also have methods, the algorithmic operations an object can perform on its data. Similarly, C++ classes also manage data and operations but use the terms data member and member function, respectively. Given an object, a program must be able to access these members. Where Java only has one selection operator, C++ provides two, dot ( .
- the period character) and arrow ( ->
- minus followed by greater-than, without spaces). The member selection operators allow programmers to select both data members and member functions.
To help compare Java to C++ and to help demonstrate the member selection operators, we begin by assuming a class named "Widget" that has a data member called "price" and a member function called "getPrice." If we further assume for now that all data and functions are public
, we can write the following statements:
Stack | Heap |
---|---|
Widget w0; cout << w0.price << endl; cout << w0.getPrice() << endl; |
Widget* w1 = new widget;
cout << w1->price << endl;
cout << w1->getPrice() << endl; |
(a) | (b) |
new
.
C++ constrains or limits the member selection operators' operands (the values appearing on either side of the operator). The left-hand operand must reference an object (an instance of a class or structure), and the right-hand operand must name one of the object's members or fields (a variable or function). Specifically, the left-hand operand cannot be a simple or fundamental data type (e.g., an int or double).
In C++, the dot operator alone is insufficient when we need to access a member through a pointer. Earlier in this chapter, we saw examples involving simple data types that required us to dereference a pointer to access the contents of the referenced memory address. We can take the same approach when accessing members: dereference the pointer first and then access the member with the dot operator: