Section 1.5. Introducing Classes


1.5. Introducing Classes

The only remaining feature we need to understand before solving our bookstore problem is how to write a data structure to represent our transaction data. In C++ we define our own data structure by defining a class. The class mechanism is one of the most important features in C++. In fact, a primary focus of the design of C++ is to make it possible to define class types that behave as naturally as the built-in types themselves. The library types that we've seen already, such as istream and ostream, are all defined as classesthat is, they are not strictly speaking part of the language.

Complete understanding of the class mechanism requires mastering a lot of information. Fortunately, it is possible to use a class that someone else has written without knowing how to define a class ourselves. In this section, we'll describe a simple class that we can use in solving our bookstore problem. We'll implement this class in the subsequent chapters as we learn more about types, expressions, statements, and functionsall of which are used in defining classes.

To use a class we need to know three things:

  1. What is its name?

  2. Where is it defined?

  3. What operations does it support?

For our bookstore problem, we'll assume that the class is named Sales_item and that it is defined in a header named Sales_item.h.

1.5.1. The Sales_item Class

The purpose of the Sales_item class is to store an ISBN and keep track of the number of copies sold, the revenue, and average sales price for that book. How these data are stored or computed is not our concern. To use a class, we need not know anything about how it is implemented. Instead, what we need to know is what operations the class provides.

As we've seen, when we use library facilities such as IO, we must include the associated headers. Similarly, for our own classes, we must make the definitions associated with the class available to the compiler. We do so in much the same way. Typically, we put the class definition into a file. Any program that wants to use our class must include that file.

Conventionally, class types are stored in a file with a name that, like the name of a program source file, has two parts: a file name and a file suffix. Usually the file name is the same as the class defined in the header. The suffix usually is .h, but some programmers use .H, .hpp, or .hxx. Compilers usually aren't picky about header file names, but IDEs sometimes are. We'll assume that our class is defined in a file named Sales_item.h.

Operations on Sales_item Objects

Every class defines a type. The type name is the same as the name of the class. Hence, our Sales_item class defines a type named Sales_item. As with the built-in types, we can define a variable of a class type. When we write

     Sales_item item; 

we are saying that item is an object of type Sales_item. We often contract the phrase "an object of type Sales_item" to"aSales_ item object" or even more simply to "a Sales_item."

In addition to being able to define variables of type Sales_item, we can perform the following operations on Sales_item objects:

  • Use the addition operator, +, to add two Sales_items

  • Use the input operator, << to read a Sales_item object,

  • Use the output operator, >> to write a Sales_item object

  • Use the assignment operator, =, to assign one Sales_item object to another

  • Call the same_isbn function to determine if two Sales_items refer to the same book

Reading and Writing Sales_items

Now that we know the operations that the class provides, we can write some simple programs to use this class. For example, the following program reads data from the standard input, uses that data to build a Sales_item object, and writes that Sales_item object back onto the standard output:

     #include <iostream>     #include "Sales_item.h"     int main()     {         Sales_item book;         // read ISBN, number of copies sold, and sales price         std::cin >> book;         // write ISBN, number of copies sold, total revenue, and average price         std::cout << book << std::endl;         return 0;     } 

If the input to this program is

     0-201-70353-X 4 24.99 

then the output will be

     0-201-70353-X 4 99.96 24.99 

Our input said that we sold four copies of the book at $24.99 each, and the output indicates that the total sold was four, the total revenue was $99.96, and the average price per book was $24.99.

This program starts with two #include directives, one of which uses a new form. The iostream header is defined by the standard library; the Sales_item header is not. Sales_item is a type that we ourselves have defined. When we use our own headers, we use quotation marks (" ") to surround the header name.

Headers for the standard library are enclosed in angle brackets (< >). Nonstandard headers are enclosed in double quotes (" ").



Inside main we start by defining an object, named book, which we'll use to hold the data that we read from the standard input. The next statement reads into that object, and the third statement prints it to the standard output followed as usual by printing endl to flush the buffer.

Key Concept: Classes Define Behavior

As we go through these programs that use Sales_items, the important thing to keep in mind is that the author of the Sales_item class defined all the actions that can be performed by objects of this class. That is, the author of the Sales_item data structure defines what happens when a Sales_item object is created and what happens when the addition or the input and output operators are applied to Sales_item objects, and so on.

In general, only the operations defined by a class can be used on objects of the class type. For now, the only operations we know we can peeform on Sales_item objects are the ones listed on page 21.

We'll see how these operations are defined in Sections 7.7.3 and 14.2.


Adding Sales_items

A slightly more interesting example adds two Sales_item objects:

      #include <iostream>      #include "Sales_item.h"      int main()      {         Sales_item item1, item2;         std::cin >> item1 >> item2;   // read a pair of transactions         std::cout << item1 + item2 << std::endl; // print their sum         return 0;      } 

If we give this program the following input

      0-201-78345-X 3 20.00      0-201-78345-X 2 25.00 

our output is

      0-201-78345-X 5 110 22 

This program starts by including the Sales_item and iostream headers. Next we define two Sales_item objects to hold the two transactions that we wish to sum. The output expression does the addition and prints the result. We know from the list of operations on page 21 that adding two Sales_items together creates a new object whose ISBN is that of its operands and whose number sold and revenue reflect the sum of the corresponding values in its operands. We also know that the items we add must represent the same ISBN.

It's worth noting how similar this program looks to the one on page 6: We read two inputs and write their sum. What makes it interesting is that instead of reading and printing the sum of two integers, we're reading and printing the sum of two Sales_item objects. Moreover, the whole idea of "sum" is different. In the case of ints we are generating a conventional sumthe result of adding two numeric values. In the case of Sales_item objects we use a conceptually new meaning for sumthe result of adding the components of two Sales_item objects.

Exercises Section 1.5.1

Exercise 1.21:

The Web site (http://www.awprofessional.com/cpp_primer) contains a copy of Sales_item.h in the Chapter 1 code directory. Copy that file to your working directory. Write a program that loops through a set of book sales transactions, reading each transaction and writing that transaction to the standard output.

Exercise 1.22:

Write a program that reads two Sales_item objects that have the same ISBN and produces their sum.

Exercise 1.23:

Write a program that reads several transactions for the same ISBN. Write the sum of all the transactions that were read.


1.5.2. A First Look at Member Functions

Unfortunately, there is a problem with the program that adds Sales_items. What should happen if the input referred to two different ISBNs? It doesn't make sense to add the data for two different ISBNs together. To solve this problem, we'll first check whether the Sales_item operands refer to the same ISBNs:

     #include <iostream>     #include "Sales_item.h"     int main()     {         Sales_item item1, item2;         std::cin >> item1 >> item2;         // first check that item1 and item2 represent the same book         if (item1.same_isbn(item2)) {             std::cout << item1 + item2 << std::endl;             return 0;    // indicate success         } else {             std::cerr << "Data must refer to same ISBN"                       << std::endl;             return -1; // indicate failure         }     } 

The difference between this program and the previous one is the if test and its associated else branch. Before explaining the if condition, we know that what this program does depends on the condition in the if. If the test succeeds, then we write the same output as the previous program and return 0 indicating success. If the test 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

     // first check that item1 and item2 represent the same book     if (item1.same_isbn(item2)) { 

calls a member function of the Sales_item object named item1. A member function is a function that is defined by a class. Member functions are sometimes referred to as the methods of the class.

Member functions are defined once for the class but are treated as members of each object. We refer to these operations as member functions because they (usually) operate on a specific object. In this sense, they are members of the object, even though a single definition is shared by all objects of the same type.

When we call a member function, we (usually) specify the object on which the function will operate. This syntax uses the dot operator (the "." operator):

     item1.same_isbn 

means "the same_isbn member of the object named item1." The dot operator fetches its right-hand operand from its left. The dot operator applies only to objects of class type: The left-hand operand must be an object of class type; the right-hand operand must name a member of that type.

Unlike most other operators, the right operand of the dot (".") operator is not an object or value; it is the name of a member.



When we use a member function as the right-hand operand of the dot operator, we usually do so to call that function. We execute a member function in much the same way as we do any function: To call a function, we follow the function name by the call operator (the "()" operator). The call operator is a pair of parentheses that encloses a (possibly empty) list of arguments that we pass to the function.

The same_isbn function takes a single argument, and that argument is another Sales_item object. The call

     item1.same_isbn(item2) 

passes item2 as an argument to the function named same_isbn that is a member of the object named item1. This function compares the ISBN part of its argument, item2, to the ISBN in item1, the object on which same_isbn is called. Thus, the effect is to test whether the two objects refer to the same ISBN.

If the objects refer to the same ISBN, we execute the statement following the if, which prints the result of adding the two Sales_item objects together. Otherwise, if they refer to different ISBNs, we execute the else branch, which is a block of statements. The block prints an appropriate error message and exits the program, returning -1. Recall that the return from main is treated as a status indicator. In this case, we return a nonzero value to indicate that the program failed to produce the expected result.



C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net