|
|
|
|
|
|
|
by another object. An object-oriented program consists of a collection of objects, communicating with one another by message passing. If object A wants object B to perform some task, object A sends a message containing the name of the object (B, in this case) and the name of the particular method to execute. B responds by executing this method in its own way, possibly changing its state and sending messages to other objects as well. |
|
|
|
|
|
|
|
|
As you can tell, an object is quite different from a traditional data structure. A C++ struct is a passive data structure that contains only data and is acted upon by a program. In contrast, an object is an active data structure; the data and the code that manipulates the data are bound together within the object. In OOP jargon, an object knows how to manipulate itself. |
|
|
|
|
|
|
|
|
The vocabulary of Smalltalk has influenced the vocabulary of OOP. The literature of OOP is full of phrases such as methods, instance variables, and sending a message to. But don't be put off by the vocabulary. Here are some OOP terms and their C++ equivalents: |
|
|
|
|
| OOP | C++ | | Object | Class object or class instance | | Instance variable | Private data member | | Method | Public member function | | Message passing | Function call (to a public member function) |
|
|
|
|
|
|
In C++, we define the properties and behavior of objects by using the class mechanism. Within a program, classes can be related to each other in various ways. The three most common relationships are: |
|
|
|
|
|
|
|
|
1. Two classes are independent of each other and have nothing in common. |
|
|
|
|
|
|
|
|
2. Two classes are related by inheritance. |
|
|
|
|
|
|
|
|
3. Two classes are related by composition. |
|
|
|
|
|
|
|
|
The first relationshipnoneis not very interesting. Let's look at the other twoinheritance and composition. |
|
|
|
|
|
|
|
|
In the world at large, it is often possible to arrange concepts into an inheritance hierarchya hierarchy in which each concept inherits the properties of the concept immediately above it in the hierarchy. For example, we might classify different kinds of vehicles according to the inheritance hierarchy in Figure 16-3. Moving down the hierarchy, each kind of vehicle is more specialized than its parent (and all of its ancestors) and is more general than its |
|
|
|
|
|