1.5.2 A First Look at Member Functions
Our program that adds two Sales_items should check whether the objects have the same ISBN. We’ll do so as follows:
- #include <iostream>
- #include "Sales_item.h"
- int main()
- {
- Sales_item item1, item2;
- std::cin >> item1 >> item2;
-
- if (item1.isbn() == item2.isbn()) {
- std::cout << item1 + item2 << std::endl;
- return 0;
- } else {
- std::cerr << "Data must refer to same ISBN"
- << std::endl;
- return -1;
- }
- }
The difference between this program and the previous version is the if and its associated else branch. Even without understanding the if condition, we know what this program does. If the condition succeeds, then we write the same output as before and return 0, indicating success. If the condition fails, we execute the block following the else, which prints a message and returns an error indicator.
What Is a Member Function
The if condition
- item1.isbn() == item2.isbn()
calls a member function named isbn. A member function is a function that is defined as part of a class. Member functions are sometimes referred to as methods.
Ordinarily, we call a member function on behalf of an object. For example, the first part of the left-hand operand of the equality expression
- item1.isbn
uses the dot operator (the “.” operator) to say that we want “the isbn member of the object named item1.” The dot operator applies only to objects of class type.
The left-hand operand must be an object of class type, and the right-hand operand must name a member of that type. The result of the dot operator is the member named by the right-hand operand.
When we use the dot operator to access a member function, we usually do so to call that function. We call a function using the call operator (the () operator). The call operator is a pair of parentheses that enclose a (possibly empty) list of arguments. The isbn member function does not take an argument. Thus,
- item1.isbn()
calls the isbn function that is a member of the object named item1. This function returns the ISBN stored in item1.
The right-hand operand of the equality operator executes in the same way—it returns the ISBN stored in item2. If the ISBNs are the same, the condition is true; otherwise it is false.
EXERCISES SECTION 1.5.2
Exercise 1.23: Write a program that reads several transactions and counts how many transactions occur for each ISBN.
Exercise 1.24: Test the previous programby givingmultiple transactions representing multiple ISBNs. The records for each ISBN should be grouped together.