Docsity

C++ Review for COP-3530 - Data Structures | COP 3530, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
C++ Review for COP-3530
This material is excerpted from Data Structures and Algorithm Analysis in C++ (Second
Edition) by Mark Allen Weiss and is copyrighted. All rights are reserved.
1C++ Classes
In this course, we will write many data structures. All of the data structures will
be objects that store data (usually a collection of identically typed items), and pro-
vide functions that manipulate the collection. In C++ (and other languages), this
is accomplished by using a class. This section describes the C++ class.
/**
* A class for simulating an integer memory cell.
*/
class IntCell
{
public:
/**
* Construct the IntCell.
* Initial value is 0.
*/
IntCell( )
{ storedValue = 0; }
/**
* Construct the IntCell.
* Initial value is initialValue.
*/
IntCell( int initialValue )
{ storedValue = initialValue; }
/**
* Return the stored value.
*/
int read( )
{ return storedValue; }
/**
* Change the stored value to x.
*/
void write( int x )
{ storedValue = x; }
private:
int storedValue;
};
Figure 1A complete declaration of an IntCell class
C++.mkr Page 1 Wednesday, December 9, 1998 7:27 AM
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download C++ Review for COP-3530 - Data Structures | COP 3530 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

C++ Review for COP-

This material is excerpted from Data Structures and Algorithm Analysis in C++ (Second Edition) by Mark Allen Weiss and is copyrighted. All rights are reserved.

1 C++ Classes

In this course, we will write many data structures. All of the data structures will be objects that store data (usually a collection of identically typed items), and pro- vide functions that manipulate the collection. In C++ (and other languages), this is accomplished by using a class. This section describes the C++ class. /**

  • A class for simulating an integer memory cell. / class IntCell { public: /*
  • Construct the IntCell.
  • Initial value is 0. / IntCell( ) { storedValue = 0; } /*
  • Construct the IntCell.
  • Initial value is initialValue. / IntCell( int initialValue ) { storedValue = initialValue; } /*
  • Return the stored value. / int read( ) { return storedValue; } /*
  • Change the stored value to x. */ void write( int x ) { storedValue = x; } private: int storedValue; };

Figure 1 A complete declaration of an IntCell class

1.1 Basic class Syntax A class in C++ consists of its members. These members can be either data or functions. The functions are called member functions. Each instance of a class is an object. Each object contains the data components specified in the class (unless the data components are static, detail that can be safely ignored for now). A member function is used to act on an object. Sometimes member functions are called methods. As an example, Figure 1 is the IntCell class. In the IntCell class, each instance of the IntCell — an IntCell object — contains a single data mem- ber named storedValue. Everything else in this particular class is a method. In our example, there are four methods. Two of these methods are read and write. The other two are special methods known as constructors. Let us describe some key features. First, notice the two labels public and private. These labels determine visibility of class members. In this example, everything except the stored- Value data member is public. storedValue is private. A member that is public may be accessed by any method in any class. A member that is pri- vate may only be accessed by methods in its class. Typically, data members are declared private, thus restricting access to internal details of the class, while methods intended for general use are made public. This is known as informa- tion hiding. By using private data members, we can change the internal repre- sentation of the object, without having an effect on other parts of the program that use the object. This is because the object is accessed through the public mem- ber functions, whose viewable behavior remains unchanged. The users of the class do not need to know internal details of how the class is implemented. In many cases having this access leads to trouble. For instance, in a class that stored dates using month, day, and year, by making the month, day, and year private, we prohibit an outsider from setting these data members to illegal dates, such as Feb 29, 2001. However, some methods may be for internal use, and can be pri- vate. In a class, all members are private by default, so the initial public is not optional. Second, we see two constructors. A constructor is a method that describes how an instance of the class is constructed. If no constructor is explicitly defined, one that initializes the data members using language defaults is automatically generated. The IntCell class defines two constructors. The first is called if no parameter is specified. The second is called if an int parameter is provided, and uses that int to initialize the storedValue member. 1.2 Extra Constructor Syntax and Accessors Although the class works as written, there is some extra syntax that makes for better code. Four changes are shown in Figure 2 (we omit comments for brevity). The differences are as follows:

IntCell obj; // obj is an IntCell obj = 37; // Should not compile: type mismatch The code fragment above constructs an IntCell object obj and then performs an assignment statement. But the assignment statement should not work, because the right-hand side of the assignment operator is not another (^) IntCell. (^) obj’s write method should have been used instead. However, C++ has lenient rules. Normally a one-parameter constructor defines an implicit type conversion , in which a temporary object is created that makes an assignment (or parameter to a function) compatible. In this case, the compiler would attempt to convert obj = 37; // Should not compile: type mismatch into IntCell temporary = 37; obj = temporary; Notice that the construction of the temporary can be performed by using the one-parameter constructor. The use of explicit means that a one parameter con- structor cannot be used to generate an implicit temporary. Thus, since IntCell’s constructor is declared explicit, the compiler will correctly complain that there is a type mismatch. In Section 7.8, we’ll see an example where the lenient rules are helpful, but this is the exception, rather than the rule. The (^) explicit keyword is new, and not all compilers support it. However, the preprocessor can be used to replace all occurrences of explicit with white space^1 , so there’s no reason not to put explicit in your code. Constant member function A member function that examines but does not change the state of its object is an accessor. A member function that changes the state is a mutator (because it mutates the state of the object). In the typical collection class, for instance, isEmpty is an accessor, while makeEmpty is a mutator. In C++, we can mark each member function as being an accessor or a muta- tor. Doing so is an important part of the design process, and should not be viewed as simply a comment. Indeed, there are important semantic consequences. For instance, mutators cannot be applied to constant objects. By default, all member functions are mutators. To make a member function an accessor, we must add the keyword const after the closing parenthesis that ends the parameter type list. The const-ness is part of the signature. (^) const can be used with many different meanings. The function declaration can have const in three different contexts.

  1. (^) Use the following statement: #define explicit

Only the const after a closing parenthesis signifies an accessor. Other uses are described in Sections 2.2 and 2.3. In the IntCell class, read is clearly an accessor: it does not change the state of the IntCell. Thus it is made a constant member function at line 3. If a member function is marked as an accessor but has an implementation that changes the value of any data member, a compiler error is generated.^2 #ifndef IntCell_H

  1. (^) Data members can be marked mutable to indicate that const-ness should not apply to them. This is a new feature, that is not supported on all compilers. #define IntCell_H /** * A class for simulating an integer memory cell. */ class IntCell { public: explicit IntCell( int initialValue = 0 ); int read( ) const; void write( int x ); private: int storedValue; }; #endif

Figure 3 IntCell class interface, in file IntCell.h

1.3 Separation of Interface and Implementation The class in Figure 2 contains all the correct syntactic constructs. However, in C++ it is more common to separate the class interface from its implementation. The interface lists the class and its members (data and functions). The implemen- tation provides implementations of the functions. Figure 3 shows the class interface for IntCell, Figure 4 shows the imple- mentation, and Figure 5 shows a main routine that uses the IntCell. Some important points follow: Preprocessor commands The interface is typically placed in a file that ends with .h. Source code that requires knowledge of the interface must #include the interface file. In our case, this is both the implementation file and the file that contains (^) main. Occa- sionally, a complicated project will have files including other files, and there is

#include "IntCell.h" int main( ) { IntCell m; // Or, IntCell m( 0 ); but not IntCell m( ); m.write( 5 ); cout << "Cell contents: " << m.read( ) << endl; return 0; }

Figure 5 Program that uses IntCell in file TestIntCell.cpp

Signatures must match exactly The signature of an implemented member function must match exactly the signa- ture listed in the class interface. Recall that whether a member function is an accessor (via the const at the end) or a mutator is part of the signature. Thus an error would result if, for example, the const was omitted from exactly one of the read signatures in Figures 3 and 4. Note that default parameters are specified in the interface only. They are omitted in the implementation. Objects are declared like primitive types In C++, an object is declared just like a primitive type. Thus, the following are legal declarations of an IntCell object: IntCell obj1; // Zero parameter constructor IntCell obj2( 12 ); // One parameter constructor On the other hand, the following are incorrect: IntCell obj3 = 37; // Constructor is explicit IntCell obj4( ); // Function declaration The declaration of obj3 is illegal because the one-parameter constructor is explicit. It would be legal otherwise. (In other words, a declaration that uses the one parameter constructor must use the parentheses to signify the initial value.) The declaration for obj4 states that it is a function (defined elsewhere) that takes no parameters and returns an IntCell. 1.4 vector and string The new C++ standard defines two classes: the vector and string. vector is intended to replace the built-in C++ array that causes no end of trouble. The

problem with the built-in C++ array is that it does not behave like a first-class object. For instance, built-in arrays cannot be copied with =, a built-in array does not remember how many items it can store, and its indexing operator does not check that the index is valid. The built-in string is simply an array of characters, and thus has the liabilities of arrays plus a few more. For instance == does not correctly compare two strings. The vector and string classes in the STL treat arrays and strings as first- class objects. A vector knows how large it is. Two string objects can be compared with ==, <, and so on. Both vector and string can be copied with =. If possible, you should avoid using the built-in C++ array and string. Because this is not always possible, we discuss the built-in array and string in Section 2.6. Unfortunately, the vector does not come with index-range checking, and is also not available on all compilers. Fortunately, it is easy to write a vector class with bounds-checks, and a reasonable subset of vector features is provided in Appendix B. We use that class throughout. Likewise, the string class is not universally available; we provide a simple version in Appendix B. vector and string are easy to use. The code in Figure 6 reads a bunch of strings into a vector (notice that we specify the type of vector) and then outputs them in reverse order. We use the resize method to double the vector’s capacity if it is full. Notice also, that size is a method that returns the size of the vector. Without a vector and string class, this code would be much more complex. #include <iostream.h> #include "vector.h" // vector (our version, in Appendix B) #include "mystring.h" // string (our version, in Appendix B) int main( ) { vector v( 5 ); int itemsRead = 0; string x; while( cin >> x ) { if( itemsRead == v.size( ) ) v.resize( v.size( ) * 2 ); v[ itemsRead++ ] = x; } for( int i = itemsRead - 1; i >= 0; i-- ) cout << v[ i ] << endl; return 0; }

Figure 6 Using the vector class: Read some strings and output them in reverse

order.

Declaration Line 1 illustrates the declaration of m. The * indicates that m is a pointer variable; it is allowed to point at an IntCell object. The value of m is the address of the object that it points at. m is uninitialized at this point. In C++, no such check is performed to verify that m is assigned a value prior to being used (however, sev- eral vendors make products that do additional checks, including this one). Use of uninitialized pointers typically crash programs because they result in access of memory locations that do not exist. In general, it is a good idea to provide an ini- tial value, either by combining lines 1 and 2, or by initializing m to the NULL pointer. Dynamic object creation Line 2 illustrates how objects can be created dynamically. In C++ new returns a pointer to the newly created object. In C++, there are two ways to create an object using its zero-parameter constructor. Both of the following would be legal: m = new IntCell( ); // OK m = new IntCell; // Preferred in this text We generally use the second form because of the problem illustrated by obj4 in Section 1.2. Garbage collection and delete In some languages, when an object is no longer referenced, it is subject to auto- matic garbage collection. The programmer does not have to worry about it. C++ does not have garbage collection. When an object that is allocated by new is no longer referenced, the delete operation must be applied to the object (through a pointer). Otherwise, the memory that it consumes is lost (until the program termi- nates). This is known as a memory leak. Memory leaks are, unfortunately, com- mon occurrences in many C++ programs. Fortunately, many sources of memory leaks can be automatically removed with care. One important rule is to not use new when an automatic variable can be used instead. In the original program, the IntCell was not allocated by new, but instead was allocated as a local vari- able. Its memory is automatically reclaimed when the function in which it was declared returns. The delete operator is illustrated at line 5. Assignment and comparison of pointers Assignment and comparison of pointer variables in C++ is based on the value of the pointer, meaning the memory address that it stores. Thus two pointer vari- ables are equal if they point at the same object. If they point at different objects, the pointer variables are not equal, even if the objects being pointed at are them- selves equal. If lhs and rhs are pointer variables (of compatible types), then lhs=rhs makes lhs point at the same object that rhs points at.

Accessing members of an object through a pointer If a pointer variable points at a class type, then a member of the object being pointed at can be accessed via the -> operator. This is illustrated at line 3. Other pointer operations C++ allows all sorts of bizarre operations on pointers that are occasionally useful. For instance, < is defined. For pointers lhs and rhs, lhs<rhs is true if the object pointed at by lhs is stored at a lower memory location than the object pointed at by rhs. There is rarely a good reason to use this construct. However, one example of an equally unusual operation is illustrated in Section 7.8. One important operator is the address-of operator &. This operator returns the memory location where an object resides and is useful for implementing an alias test that is discussed in Section 2.5. 2.2 Parameter Passing Many languages, C and Java included, pass all parameters using call by value: the actual argument is copied into the formal parameter. However, parameters in C++ could be large complex objects, for which copying is inefficient. Additionally, sometimes it is desirable to be able to alter the value being passed in. As a result of this, C++ has three different ways to pass parameters. However, there is a sim- ple rule to decide which method to use. The three parameter passing mechanisms are illustrated in the following function declaration that returns the average of the first n integers in arr, and sets errorFlag to true if n is larger then arr.size() or smaller than 1. double avg( const vector & arr, int n, bool & errorFlag ); Here arr is of type vector and is passed using call by constant ref- erence , n is of type int and is passed using call by value , and errorFlag is of type bool and is passed using call by reference. The parameter passing mecha- nism can generally be decided by a two-part test.

  1. If the formal parameter should be able to change the value of the actual argument, then you must use call by reference.
  2. Otherwise, the value of the actual argument cannot be changed by the formal parameter. If the type is a primitive type, use call by value. Otherwise, the type is a class type and would generally be passed using call by constant reference.^3
  3. (^) However, class types that are small (for instance, those that store only a single built-in type) can be passed using call by value instead of call by constant reference.

overhead of a copy.^4 However, this is only possible if it is guaranteed that the expression in the return statement has lifetime that extends past the return of the function. This is a very tricky part of C++, and many compilers will fail to give a warning message for incorrect use. As an example, consider the code in Figure 8, which contains two nearly identical functions to find the largest (alphabetically) string in an array. Both attempt to return the value by constant reference. The first version, findMax, shows acceptable use: the expression a[maxIndex] indexes a vector that already exists outside of findMax, and will exist long after the call returns. The second version is wrong. maxValue is a local variable that does not exist when the function returns. Thus it is improper to return without making a copy of it. If the compiler fails to complain, then the return value may or may not contain use- ful information, depending on how quickly the compiler decides to reclaim the memory that was used by maxValue. This makes for a difficult debugging job. 2.4 Reference Variables References and constant reference variables are commonly used for parameter passing. But they can also be used as local variables or as class data members. In these cases, they variable names become synonyms for the objects that they refer- ence (much like the formal parameters become synonyms for actual arguments in call by reference). As local variables, they avoid the cost of a copy and thus are useful when querying a data structure that contains a collection of class types. Thus, in many cases, client code such as string x = findMax( a ); ... cout << x << endl; is better written as const string & x = findMax( a ); ... cout << x << endl; A second use, that we will see in Chapter 5, is to use a local reference vari- able solely for the purpose of renaming an object that is known by a complicated expression. The code we will see is similar to the following: List & whichList = theLists[ hash( x,theLists.size() ) ]; ListItr itr = whichList.find( x ); if( itr.isPastEnd( ) ) whichList.insert( x, whichList.zeroth( ) );

  1. (^) The const here means that the object being returned cannot itself be modified later on. It is different from the const in the parameter list and the const that signifies an accessor.

A reference variable is used so that the considerably more complex expression, theLists[hash(x,theLists.size())], does not have to be written three times. Reference variables can be used as class data members, though we do not do this in the text (however, an Exercise in Chapter 3 suggests a design that uses a reference variable as a data member). References must be initialized by the con- structor to the object that they will reference. 2.5 The Big Three: destructor, copy constructor, operator= In C++, classes come with three special functions that are already written for you. These are the destructor , copy constructor , and operator=. In many cases you can accept the default behavior provided by the compiler. Sometimes you cannot. Destructor The destructor is called whenever an object goes out of scope or is subjected to a delete. Typically, the only responsibility of the destructor is to free up any resources that were allocated during the use of the object. This includes calling delete for any corresponding news, closing any files that were opened, and so on. The default simply applies the destructor on each data member. Copy constructor There is a special constructor that is required to construct a new object, initialized to a copy of the same type of object. This is the copy constructor. For any object, such as an IntCell object, a copy constructor is called in the following instances:

  • a declaration with initialization, such as IntCell B = C; IntCell B( C ); but not B = C; // Assignment operator, discussed later
  • an object passed using call by value (instead of by & or const &), which, as mentioned earlier, should never be done anyway.
  • an object returned by value (instead of by & or const &) The first case is the simplest to understand because the constructed objects were explicitly requested. The second and third cases construct temporary objects that are never seen by the user. Even so, a construction is a construction, and in both cases we are copying an object into a newly created object.

operator= is the most interesting. Line 1 is an alias test, to make sure we are not copying to ourselves. Assuming we are not, we apply operator= to each data member (at line 2). We then return a reference to the current object, at line 3, so assignments can be chained, as in a=b=c. In the routines that we write, if the defaults make sense, we will always accept them. However, if the defaults do not make sense, we will need to imple- ment the destructor, and operator=, and the copy constructor. When the default does not work, the copy constructor can generally be implemented by mimicing normal construction and then calling operator=. Another often-used option is to give a reasonable working implementation of the copy constructor, but then place it in the private section, to disallow call by value. When The Defaults Do Not Work The most common situation in which the defaults do not work occurs when a data member is a pointer type, and the pointee is allocated by some object member function (such as the constructor). As an example, suppose we implement the IntCell by dynamically allocating an int, as shown in Figure 10. For simplic- ity, we do not separate the interface and implementation. IntCell::~IntCell( ) { // Does nothing since IntCell contains only an int data // member. If IntCell contained any class objects their // destructors would be called. } IntCell::IntCell( const IntCell & rhs ) { } const IntCell & IntCell::operator=( const IntCell & rhs ) { /* 1/ if( this != &rhs ) // Standard alias test / 2/ storedValue = rhs.storedValue; / 3*/ return *this; } Figure 9 The defaults for the big three

class IntCell { public: explicit IntCell( int initialValue = 0 ) { storedValue = new int( initialValue ); } int read( ) const; { return *storedValue; } void write( int x ); { *storedValue = x; } private: int *storedValue; }; Figure 10 Data member is a pointer; default are no good There are now numerous problems that are exposed in Figure 11. First, the output is three 4 s, even though logically only a should be 4. The problem is that the default operator= and copy constructor copy the pointer storedValue. Thus a.storedValue, b.storedValue, and c.storedValue all point at the same int value. These copies are shallow : the pointers, rather than the pointees are copied. A second less-obvious problem is a memory leak. The int initially allocated by a’s constructor remains allocated and needs to be reclaimed. The int allocated by b and c’s constructor is no longer referenced by any pointer variable. They also need to be reclaimed, but we no longer have a pointer to it. To fix these problems, we implement the big three. The result (with the inter- face and implementation separated) is shown in Figure 12. Generally speaking, if a destructor is necessary to reclaim memory, then the defaults for copy assign- ment and copy construction are not acceptable. If the class contains data members that do not have the ability to copy them- selves, then the default operator= will not work. We will see some examples of this later in the text. int f( ) { IntCell a( 2 ); IntCell b = a; IntCell c; c = b; a.write( 4 ); cout << a.read( ) << endl << b.read( ) << endl << c.read( ) << endl; return 0; } Figure 11 Simple function that exposes problems in Figure 10

2.6 The World of C C++ inherits its basic syntax from C. Some C-style constructs are occasionally seen in C++, even though C++ provides alternatives. We list a few of these. structs In C++, a struct is exactly like a class except that by default, all members are public. There is no other semantic difference. As a result, it is easy to write a C++ program that never uses struct. Even so, a struct is commonly used to signal a class that contains only public data and constructors, since such a class behaves like a C-style struct. typedef The typedef is used to indicate that a symbol should be a synonym for an exist- ing type. For instance, typedef string * ptr_to_string; says that ptr_to_string is a synonym for the string* type. typedef is less-often used in C++ than C because in many cases it is better to define a new class that encapsulates the behavior of this type that to use a typedef. There are two common uses of the typedef. One is to define system- dependent information. Thus, the type int32, representing a thirty-two bit inte- ger, could be a typedef defined in a header file. On some machines it would be an int, on others it could be a short, and on others it could be a long. A sec- ond use is to provide a synonym for a long type name. Long type names are com- mon when templates (especially in the STL) are instantiated. An example of this is in Appendix A. Parameter Passing: C-Style In C, all parameters are passed using call-by-value. However, C programmers often need to pass using call-by-reference. Since this is not possible in C, a com- monly used trick is used: a pointer to the object is passed instead of the object. Call-by-value means that the value of the pointer (where it points) cannot change, but does not disallow changing the pointee. To illustrate the idiom, we show how an integer is passed by reference. The function zero will change the object being pointed at to 0. zero declares: void zero( int *val ) { *val = 0; } The function call is made by passing the address of x to function zero: int x = 5; // Object x has value 5 zero( &x ); // Object x will have value 0

Passing using C++ call by reference is preferable to this idiom. However, many libraries are written to work with both C and C++, and thus pass variables using the C-style. Thus you may need to use this idiom. We do not use elsewhere in the text. C-Style Arrays and Strings The C++ language provides a built-in C-style array type. To declare an array, arr, of ten integers, one writes: int arr1[10]; arr1 is actually a pointer to memory that is large enough to store 10 ints, rather than a first-class array type. Applying = to arrays is thus an attempt to copy two pointer values, rather than the entire array, and with the declaration above is illegal because arr1 is a constant pointer. When arr1 is passed to a function, only the value of the pointer is passed; information about the size of the array is lost. Thus the size must be passed as an additional parameter. There is no index range checking, since the size is unknown. In the declaration above, the size of the array must be known at compile time. 10 cannot be replaced by a variable. If the size is unknown, we must explicitly declare a pointer and allocate memory via new[]. For instance, int *arr2 = new int[ n ]; Now arr2 behaves like arr1 except that it is not a constant pointer. Thus it can be made to point at a larger block of memory. However, because memory has been dynamically allocated, at some point it must be freed with delete[]: delete [ ] arr2; Otherwise, a memory leak would result, and the leak could be significant, if the array is large. Built-in C-style strings are implemented as an array of characters. To avoid having to pass the length of the string, the special null-terminator '\0' is used as a character that signals the logical end of the string. Strings are copied by strcpy, compared with strcmp, and their length can be determined by strlen. Individual characters can be accessed by the array indexing operator. These strings have all the problems associated with arrays, including difficult memory management, compounded by the fact that when strings are copied, it is assumed that the target array is large enough to hold the result. When it is not, dif- ficult debugging ensues, especially when room has not be left for the null termi- nator. Appendix B describes a vector class and a string class, that are imple- mented by hiding the behavior of the built-in C-style array and string. By study- ing that class, you can see how C-style arrays and strings are manipulated. It is