Software Development in C++
Software Development in C++
Lecture Notes
Peter Grogono
These notes may be copied for students who are taking either of these courses:
Contents
1 Getting Started 1
1.1 Hello, world! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Compiling C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5 Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.6 Loop Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.1 Counting Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.6.2 Finding Roots by Bisection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.6.3 Maximum Subsequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.7 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.8 Oh Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3 Batches of Data 36
3.1 Lvalues and Rvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2 Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3 Reading Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.4 Reading from a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.4.1 Writing to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.5 Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.2 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6 Template Programming 84
6.3 Complications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
11 Potpourri 193
B Glossary 236
References 243
LIST OF FIGURES vii
List of Figures
1 Hello.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
5 Hello.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
6 Hello.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
7 Greeting.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8 Greeting.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
9 Greeting.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
11 Fencepost numbering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
18 Solving equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
19 Passing arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
25 Output manipulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
31 Function showClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
LIST OF FIGURES viii
32 Class Student . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
35 Comparison functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
45 Dangerous tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
48 Properties of iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
71 Arithmetic operators for class Rational, implemented using the arithmetic assign-
ments of Figure 68 on page 118 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
1 Getting Started
Although this course will cover programming practices in general, the focus will be on C++. Why
not Java?
• C++ is more complex than Java. If you can write good programs in C++ well, you can transfer
this skill to Java; the converse is not true.
• Although Java has achieved widespread popularity during the last ten years, there is still a
need for C++ programmers.
Many games and most software for the telecommunications industry is written in C++. Com-
panies that use C++ include (see also the course web page): Adobe products; Alias/Wavefront
products (e.g., Maya); Amazon; Google; JPL/NASA; and Microsoft.
• There are many Java jobs and many Java programmers. There are not quite so many C++ jobs
and there are very few good unemployed C++ programmers. Strong C++ programmers can find
interesting and well-paid jobs.
It is a cliché to say that software is becoming ubiquitous. However, it is noteworthy that programs
are getting larger:
The crucial problem for all aspects of software development is scalability. Approaches and tech-
niques that do not work for millions of lines of code are not useful.
The C Programming Language (Kernighan and Ritchie 1978), the “classic” text for C, appeared in
1978. Its first example program has set the standard for all successors:
main()
{
printf("hello, world\n");
}
Since then, C has evolved considerably: it has even changed its name, to C++. Accelerated C++ begins
with the version of the “hello, world” program shown in Figure 1 (Koenig and Moo 2000, page 1).
1 GETTING STARTED 2
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
Figure 1: Hello.1
A modern C++ compiler should compile both programs, because C++ is an extension of C.1 To be
more precise, it was originally the intention that C++ and C should be compatible, but that goal was
abandoned when it became clear that C++ would suffer if it was followed rigorously: it is possible
to write programs that are legal C but not legal C++. An unfortunate side-effect of this compatibility
is that there is now a mixture of C and C++ programming styles, ranging from “classic C” style to
“modern C++” style. In this course, we will emphasize the modern style.
• #include <iostream> informs the compiler that the program uses components from
the stream library to perform input and output.
• int main() introduces a function that is usually called the main program. Compilers are
quite flexible about the declaration of this function. We will see later, for example, that main
may take arguments. The initial int is important, however: it indicates that the function will
return an integer that the operating system may use to choose the next action.
• std::cout is the new version of the old “printf”. The first part, std, refers to a names-
pace in which cout and other names are declared. cout (pronounced “see-out”) is the name
of the standard output stream; when a program runs, text written to cout appears on the
console window. The :: is a scoping operator that says, in effect, “find the name cout in the
namespace std”.
• << is an operator, analogous to + or ×. In this case, its right operand consists of stuff to be
written to standard output.
• std::endl is the new version of \n: it is short for “end line” and outputs a return character.
(We can still use \n, however.)
• return 0 sends zero back to the operating system, indicating that the program terminated
successfully.
C has a reputation for being cryptic. The following code for copying a string (Kernighan and Ritchie
1978, page 101) is often quoted:
char *s;
char *t;
....
while (*s++ = *t++)
;
This works for several rather subtle reasons: the post-increment operator ++ has an effect and also
returns a value; the assignment operator = returns a value; C strings are terminated by the special
value ’\0’ (also known as the “null character”); and the null character, interpreted as a boolean,
represents false. The loop terminates because a C string, by convention, is terminated with a
null character (’\0’).
This style of programming was fine for the time. Ritchie designed C for systems programming on
minicomputers of the early 1970s. He did most of his work on a DEC PDP/11 with 64 Kb of RAM
and he wanted a small and simple compiler. The while statement above can be compiled into
efficient code without any further optimization.
By way of contrast, here is the string copy implemented in “C-for-dummies” style. Note the explicit
termiantion test, comparing s[i] to ’\0’:
int i = 0;
do
{
s[i] = t[i];
i = i + 1;
} while (s[i] != ’\0’);
An experienced C programmer would probably prefer the library function strcpy to either of
these versions.
From a modern perspective, however, the while statement is unnecessarily cryptic and poten-
tially inefficient because it places unnecessary constraints on what the compiler can do. Accurately
implementing what the programmer has written requires the use of two registers, separately incre-
mented, and each containing a pointer. At each cycle, the code must test for a null character.
std::string s;
std::string t;
....
s = t;
In this version, strings are instances of a standard class string rather than “pointers to char-
acters”. The copying operation is performed by the library function that implements assignment
(“=”). This function can be written to be optimal for the architecture for which the library is written:
for example, it might use “block moves” rather than copying characters one at a time. It might even
1 GETTING STARTED 4
avoid copying altogether (see Figure 2). The code does not depend on any particular representa-
tion for strings. For example, it does not require a null terminating character. In general, a C++
programmer will tend to work at a higher level of abstraction than a traditional C programmer.
Figure 2 shows the time required to copy a 44-character string2 in the four different ways described
above. All times are in microseconds. The results are surprising: strcpy is 34 times faster
than string assignment with VC++, but 27 times slower with gcc. Perhaps Microsoft have not
implemented the new libraries very well! It seems likely that gcc avoids copying the string until it
becomes necessary (i.e., it uses the “copy on write” pattern). The standard class string is widely
considered to be an inefficient mess, so perhaps we should not worry too much about these results.
Here is another, much more advanced, example of modern C++. Suppose we want to parse strings
according to the following grammar:
Using the Boost Spirit library (Abrahams and Gurtovy 2005), we can write code corresponding to
these productions as shown in Figure 3 follows (some additional surrounding code is needed to
make everything work). Notice how close the C++ code is to the original grammar.
That C++ is compatible with C is both good and bad. It is good because at Bell Labs, where C++
was developed, a new language that could not compile existing code would almost certainly have
not been accepted. It is bad because C is an old language with many features that would now be
considered undesirable; compatibility meant that C++ had to incorporate most of these undesirable
features, even though it does quite a good job of covering them up. A well-trained and conscientious
programmer can write secure and efficient programs in C++; an inexperienced programmer can
create a real mess.
2
"the quick brown fox jumped over the lazy dog".
1 GETTING STARTED 5
expr =
( term[expr.val = _1] >> ’+’ >> expr[expr.val += _1] )
| ( term[expr.val = _1] >> ’-’ >> expr[expr.val -= _1] )
| term[expr.val = _1]
;
term =
( factor[term.val = _1] >> ’*’ >> term[term.val *= _1] )
| ( factor[term.val = _1] >> ’/’ >> term[term.val /= _1] )
| factor[term.val = _1]
;
factor =
integer[factor.val = _1]
| ( ’(’ >> expr[factor.val = _1] >> ’)’ )
;
The Boost/Spirit example illustrates another aspect of modern C++. All competent C programmers
are essentially equal: they all have a good understanding of the entire language and its standard
libraries. With C++, however, a wide gulf separates programmers who can use the Spirit parser
components — which is straightforward — from the programmers who can create the Spirit com-
ponents; these programmers form a small minority of C++ programmers. (Parser generators are
constructed by template metaprogramming, which few C++ programmers understand, let alone
use.)
Old compilers, and even some new compilers, are not able to compile modern C++ programs. Fig-
ure 4 lists compilers that work in the left column and compilers that may not work in the right
column.
Compiling a program consists of a number of steps. Errors may occur at any step, and it is impor-
tant to distinguish the different kinds of error. The compiler processes the program as a number of
compilation units. Each compilation unit corresponds to a source code file together with any other
files #included with it.
1. The compiler parses each compilation unit. This may produce syntax errors.
If we omit a semicolon in Figure 1, writing
f:\Courses\COMP6441\src\Hello\hello.cpp(32):
error C2143: syntax error : missing ’;’ before ’}’
The “32” is the number of the line on which the error is detected; in this case, it is the line
containing }, the line following the line with the error. However, the error message itself is
quite helpful: it actually tells you what is wrong with your program.
2. The compiler checks the semantic correctness of the program. For example, is each function
called with arguments of an appropriate type? This may produce semantic errors.
If we omit the “l” from “endl”, the compiler issues two semantic errors:
f:\Courses\COMP6441\src\Hello\hello.cpp(31):
error C2065: ’end’ : undeclared identifier
f:\Courses\COMP6441\src\Hello\hello.cpp(31):
error C2593: ’operator <<’ is ambiguous
Syntax errors and semantic errors are collectively call compile-time errors.
4. When each compilation unit has been controlled, the linker is invoked. The linker attempts to
link all of the object code modules together to form an executable (or, occasionally, a library).
This may produce link-time errors.
Suppose that we declare and use a function f but forget to define it. The compiler expects
that f will be defined somewhere else and so does not generate a semantic error. We do not
get an error until the linker discovers that there is no definition:
The mysterious string ?f@@YAXH@Z is the name that the compiler has given to the func-
tion f. The conversion from f to ?f@@YAXH@Z is called name mangling.
5. When the program has been linked, it can be executed or, more simply, run. It may run
correctly or it may generate run-time errors.
If you write cout twice by mistake, the compiler accepts the program without any fuss:
0045768CHello, world!
Output like this can be disconcerting for beginners: the program has displayed the address
of the object cout in hexadecimal!
Although you don’t really want any errors at all, you should prefer compile-time and link-time
errors to run-time errors, if only because your customers will never see them. Fortunately, C++
compilers perform thorough syntactic and semantic checking (much better than C compilers) and
will catch many of your errors.
By default, VC++ tries to include all kinds of Microsoft junk. You can use this stuff if you want to,
but the programs discussed in the course will be written in plain old vanilla C++. Use the following
steps to create simple C++ programs:
1. Start VC++.
4. You should now have, at top right, a window called Solution Explorer. Your project
name appears as the root of a tree.
5. Right click on the project name, and select Add/Add new item from the drop-down
menu. (The second icon on the main tool-bar has the same effect.) This should open a new
window called Add New Item.
6. In the Add New Item window, select C++ File (.cpp). Provide a name for your
source file in the box provided and click Open. This should give you a blank window in which
to enter your code. If you see default code written by Microsoft, you have done something
wrong.
9. Select Debug/Start without debugging (or press ctrl-F5) to run your program.
If you have already have a C++ file and you awnt to use it in a project, carry out the first four steps
as above. Instead of step 5, click on Project/Add existing item and select the file(s) you
want in your project.
Using gcc under unixTM or Linux is much easier: just enter gcc (or perhaps g++) followed by
options and file names. For any but the most trivial projects, you will probably find it easier to
write a make file.
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
“#include” is a compiler directive. Strictly speaking, it is not part of the program, but instead is
an instruction telling the compiler what to do. In this case, the directive tells the compiler to make
the part of the standard library that deals with streams accessible to the program.
1 GETTING STARTED 9
Streams are one of the media that C++ programs used to communicate. The communication is
usually external — data is read to or from a device such as a keyboard, screen disk, or network —
but may also be internal to the program. A stream is not the same as a file, although a file may be
read or written with a stream.
An output stream typically allows the program to send data to an external device, such as a window.
An input stream typically allows the program to receive data from an external device, such as a
keyboard. The library component iostream provides both: “i” for input and “o” for output.
The program itself consists of a single function definition. The function’s name is main and its
return type is int. The word int is a keyword of C++, meaning that we cannot use it for anything
other than its intended application. In fact, int is a type — the type of signed integers. A value i
of type int is typically represented using 32 bits and satisfies −231 ≤ i < 231 − 1.
The body of the function consists of a sequence of statements (two in this example) enclosed in
braces ({ ... }). The last character of each statement is a semi-colon (;).
The return type of the function (int) is related to its last statement: return 0. The program
behaves as if the function main is invoked by the operating system, executes its two statements,
and returns the integer 0 as its result. The operating system interprets 0 as “normal termination”.
We can return other values if we want to tell the operating system that something went wrong.
The only thing left to discuss is the line beginning with std::cout. This illustrates an important
general principle of C++. The text
is an expression that yields a value. By putting a semicolon at the end of this expression, we discard
the value and turn the expression into a statement.
Expressions consist of operands and operators. For example, x + 5 is an expression with two
operands (x and 5) and one operator, +. We say that + is a binary operator because it takes
two operands: x is its left operand and 5 is its right operand. An expression can be evaluated to
yield a result. If x has the value 2, then evaluating x + 5 yields 7.
In C++, << is a binary operator, usually called “insert”. Its left operand is an output stream; its right
operand may be a string, a manipulator, and various other things. Its result is a stream. When an
expression contains more than one insertion operator, they are evaluated fom left to right. The first
step in evaluating
is to evaluate
This has the effect of appending the string "Hello, world!" to the standard output stream
and yields the updated output stream, say uos. The next step is to evaluate
which has the effect of appending a new line to the standard output stream (and a bit more, dis-
cussed below) and yields the updated output stream. In the program, this expression is followed
by a semicolon, which throws away the final value. cout is a persistent object, however, and it still
exists in its updated state.
and
The difference is that std::endl writes the \n and also flushes the output buffer. What does this
mean?
It would be inefficient for a program to go through all of the operations of transferring data for
every character in a stream. To save time, the program stores characters in a temporary area called
a buffer and performs the actual transfers only when the buffer is full. If the program is writing
data to a file, this behaviour is undetectable to the user. But, if the program is writing to a window,
buffering makes a lot of difference. If we use \n, a significant amount of output may be generated
by the program before we actually see it displayed. Using std::endl ensures that each line of
output will be displayed as soon as it has been computed.
When C++ sees a quote (") at the end of a string, followed by white space (blanks, tabs, and line
breaks), followed by a quote at the beginning of a string, it erases quotes and the white space and
treats the result as a single string. This is useful for writing long strings or strings that run over
several lines.
1.4 Namespaces
As we noted above, we write std::cout to tell the compiler that the name cout comes from
the namespace std. The name cout is a simple name (or just a name), std::cout is a qualified
name, and std:: is a qualifier.
We can use this convention but, as programs get longer and more complex, the frequent appearance
of “std::” becomes irritating, as well as being tedious to type. An alternative is to say to the
compiler “When I write cout, I mean std::cout”. This is the purpose of the using directive,
1 GETTING STARTED 11
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello, world!" << endl;
}
Figure 5: Hello.2
#include <iostream>
int main()
{
cout << "Hello, world!" << endl;
}
Figure 6: Hello.3
as shown in Figure 5. In general, we write one using directive at the beginning of the source file
for each name that we intend to use.
We can go further, saying to the compiler “When I write any name that belongs to std, take it from
there”. The form of the using directive that does this is shown in Figure 6. Note that, in both
Figure 5 and Figure 6, we use cout and endl without the qualifier std::.
Some people will tell you that the point of namespaces is to make the source of names explicit; they
will tell you that Figure 1 is the best way to write programs, Figure 5 is acceptable, and Figure 6 is
bad — the kind of code produced by lazy programmers who should be fired. This attitude is wrong.
The actual situation is more complex.
Namespaces were introduced into C++ to prevent name clashes in programs that use more than one
library. Suppose that you are writing a program that uses a library Cowboy and another library
Artist. Both libraries provide a function called draw. When you try to use draw, the compiler
complains that it cannot tell which library to take it from. To avoid this problem, the libraries wrap
their names in namespaces — perhaps namespace cowboy and namespace artist. The
programmer can then write cowboy::draw or artist::draw, depending on which function
is needed.
Most of the time, however, name clashes do not occur. In particular, it is very unlikely that a library
writer would use a well-known name such as cout. Consequently, it is quite acceptable to use the
form of Figure 6, while being aware that it may one day be necessary to use explicit qualification
when a name clash actually occurs.
1 GETTING STARTED 12
1.5 Strings
Figure 7 (Koenig and Moo 2000, page 9) shows a program that asks for the user’s name and then
greets the user. Running it produces a dialogue like this:
Much of this program should already be familiar because it is similar to Hello, world!. The
new features are the class string and the input stream cin.
#include <iostream>
#include <string>
int main()
{
cout << "What is your name? ";
string name;
cin >> name;
cout << "Hi, " << name << "!" << endl;
return 0;
}
Figure 7: Greeting.1
The directive #include <string> informs the compiler that we will be using class string.
Since the names provided by string are included in the namespace std, we can write simply
“string” in the program rather than “std::string”.
string name;
is both a declaration and a definition. (We will discuss the distinction between declarations and
definitions in detail later. For now, note that all definitions are also declarations, but a declaration
is not necessarily a definition.) It introduces a new variable, name, into the program. The type of
name is string. We could also say that name is a new object, and an instance of class string.
The value of a string object is a string of characters, such as "Hello, world!". After the
declaration, the value of name is actually the empty string, written "".
There are various ways of putting characters into a string. In this program, the statement
reads data from the standard input stream, cin (pronounced “see-in”). By default, cin gets
data from the keyboard. In other words, whatever text you enter in response to the prompt
"What is your name?" gets stored in the variable name.
Actually, this description is not quite accurate: cin reads only until it encounters white space (a
blank, tab, or enter) and then stops. This explains the following dialogue:
After the program has stored a value in name, it can use this value, as in the second cout state-
ment.
There is a subtlety in Figure 7 that is worth noting. On the basis of the discussion at the end of
Section 1.3, you would be right to wonder why the statement
produces any output at all. Why is the data not left in the buffer until endl is output in the second
cout statement? The answer is that the streams cin and cout are linked. Any use of cin causes
the buffer for cout to be flushed. This ensures that programs that implement a dialog in which
the user must respond to displayed text will work as expected.
Memory management is an important aspect of C++ programming. In Figure 7, memory for the
string name is allocated on the run-time stack when the definition string name is evaluated.
The class string manages memory when characters are put into the string (e.g., by cin) or the
string is changed in other ways. At the final closing brace (“}”) of the program, any memory used
by name is de-allocated.
A definition, of a variable or other named entity, occurs within a scope. The scope consists either
of the closest enclosing braces or, if there are no enclosing braces, the entire source file. In the
latter case, we say that the definition is “at file scope”. Uses of the name must follow its definition.
In other words, we cannot refer to a variable earlier in the program text than its definition: this is
called the “definition before use rule”. The name ceases to be accessible at the end of its scope.
In many cases, there are actions connected with the definition and the end of the scope. In Figure 7,
which is typical, the object name is constructed at the point of its definition and destroyed at
the end of the program. What actually happens is this: when an object definition is processed, a
constructor for the object is called and, at the end of a scope, the destructors for all stack-allocated
objects are called.
Some C++ programmers (and books) use the abbreviations “ctor” and “dtor” for constructor and
destructor, respectively.
1 GETTING STARTED 14
#include <iostream>
#include <string>
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
return 0;
}
Figure 8: Greeting.2
The greeting produced by Figure 7 is dull and boring. The next version, in Figure 8 (Koenig and Moo
2000, page 12), produces dialogues like this:
************************
* *
* Hi there, Ferdinand! *
* *
************************
The new feature in this program is const string. There are four definitions of the form
The keyword const tells the compiler that the values of the names are not going to change. We
cannot declare name as const because its initial value ("") gets changed when we use cin to
copy characters into it.
1 GETTING STARTED 15
When we introduce a const name, we must provide a value for it in the same declaration. The
value can be a simple value, as in this example:
Figure 8 shows several other ways of providing an initial value using features of class string:
• spaces(greeting.size(), ’ ’)
The expression greeting.size() makes use of a member function of class string.
Member functions are called with the “dot notation”:
In this case, the function name is size and it returns the size of (i.e., the number of char-
acters in) the object greeting. Thus greeting.size() is a number (in this case, it is
20).
Class string has a constructor which expects two arguments: an numeric value (type int)
and a character value (type char). By writing spaces(n, ’ ’) we are saying: construct
an instance of class string with name spaces that contains n characters where each
character is ’ ’ (that is, a blank).
Thus the effect of this particular definition is to define a constant string object spaces
with value " ". ( denotes a blank.)
• first(second.size(), ’*’)
The definition of first is similar to that of spaces. It has the same number of characters
as second, but each character is an asterisk, ’*’. Note that C++ distinguishes between
strings, which have zero or more characters between double quotes ("....") and characters
(instances of type char), which have exactly one character between single quotes (’.’).
Having defined the strings greeting, spaces, second, and first, the program uses them to
generate the desired output.
Although this program is trivial, it illustrates two important points about programming in gen-
eral:
The program is not written for people with five-letter names but for people with names of any
(reasonable!) length.
The strings needed for the display are computed (as much as possible). This makes it easy to
generate a display whose size matches the name of the user.
It is not necessary to call cout once for each line of output. The six calls of cout in Figure 8 could
be replaced by a single call:
cout <<
endl <<
first << endl <<
second << endl <<
"* " << greeting << " *" << endl <<
second << endl <<
first << endl;
2 TESTING AND LOOPING 17
The control flow of a program is determined by tests and loops. In this section, we review the main
C++ structures for testing and looping and discuss some aspects of loop design.
2.1 Conditions
A condition is an expression whose value is either true or false. (This assumes a two-valued logic.
There are other logics with more than two values. For example, the value of a formula in a three-
valued logic might be true, false, or unknown.)
C++ has a standard type, bool, with exactly two values, true and false. Type bool also
provides operators, as shown in this table:
conjunction ∧ &&
disjunction ∨ ||
negation ¬ !
C++ also has operators that work on all of the individual bits of their operands in parallel. These are
& (bitwise-and), | (bitwise-or), and ^ (bitwise-exclusive-or). Do not confuse these with the boolean
operators!
The operators && and || are lazy; this means that they do not evaluate their right operands unless
they need to. In detail, p && q is evaluated like this:
• In C++, conjunction (and) and disjunction (or) are not commutative! That is, p && q is not
always equivalent to q && p. However, they cannot yield different truth values: at worst,
one would succeed and the other would fail.
2 TESTING AND LOOPING 18
C++ also provides comparison operators, which compare two operands and yield a boolean value.
They are < (less than), <= (less than or equal to), == (equal to), != (not equal to), > (greater than),
and >= (greater than or equal to. Do not confuse == with = (the assignment operator). These work
with operands of most types but may not always make sense.
How to read C++:
x == y ≡ “X equals Y ”
a = b ≡ “A gets B” or “A becomes B” or “A is assigned B”
In addition to the type bool, C++ inherits some baggage from C. In C, and therefore in C++:
• 0 is considered false
• A condition such as counter != 0, in which counter is an integer, has the same truth-
value as counter. Many C++ programmers therefore use the simpler form, counter, in a
context where a truth value is expected.
• Expressions that are true, when considered as truth values, are not necessarily equal. For
example, suppose we want to express the fact that two counters are either both zero or both
non-zero. We could express this condition as
(counter1 == 0) == (counter2 == 0)
or, equivalently, as
(counter1 != 0) == (counter2 != 0)
counter1 == counter2
The convention also suggests the question: what is zero in C++? The answer is that there are
many things that are considered to be zero — and are therefore also considered to be false in a
condition:
• Floating point numbers of type float, double, and long double, with value 0.0
Programs typically evaluate conditions using if statements, which have one of two forms
if ( hconditioni )
hstatementi
if ( hconditioni )
hstatementi
else
hstatementi
The hstatementis in an if statement can be simple or compound. This example illustrates both
possibilities:
The braces around the final assignment, angle = 0, are not essential. We could alternatively
have written
....
else
angle = 0;
Whether you include the braces or not is a matter of taste and preference. Including them adds
two lines to the code (or one line if you put the left brace on the same line as else). But including
them makes it easy to add another line later — which is often necessary — and avoids the error of
adding a line but forgetting to add the braces.
2.3 Loops
C++ provides three looping constructs. In the order in which you should consider using them, they
are: for; while; and do/while.
while ( hconditioni )
hstatementi
?
true
hconditioni - hstatementi
false
An important feature of the while loop is that the loop body may not be executed at all. This is
a very useful feature and, when writing a while loop, you should always check that its behaviour
when the condition is initially false is correct.
hinitializei
while ( hconditioni )
{
hactioni
hstepi
}
int i = 0;
while ( i < MAX )
{
doSomething(i);
++i;
}
write this:
It is a good idea to get into the habit of using pre-increment (++i) rather than post-increment
(i++). For integers, it doesn’t make much difference, but ++ and -- are overloaded for other types
for which the difference is more significant. The reason for preferring pre-increment is that i++
may force the compiler to generate a temporary variable, whereas ++i does not.
The do/while loop is used only when you want to evaluate condition after performing the loop
body:
do
hstatementi
while ( hconditioni )
The program in Figure 9 uses if, while, and for statements. Figure 10 shows an example of its
use. The outer loop, formatting the rows of the display, is a for loop, because exactly one row is
processed during each iteration. This pattern does not work for the inner loop, because progress
is not always one column at a time. The if statements make decisions about what text to output,
and they all have complex conditions with && and || operators.
This program is easier to modify than Figure 8: to change the size of the frame, all we have to do
is change numbers in the const declarations. In fact, just changing the value of pad will change
the spacing all around the greeting. This is a good general rule:
The original program (Koenig and Moo 2000, page 29) contains a number of comments:
These comments are acceptable, but only because this program appears in an introductory text
book. In general, comments like this should not be written unless:
#include <iostream>
#include <string>
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
const string greeting = "Hello, " + name + "!";
const int pad = 1;
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl;
for (int r = 0; r != rows; ++r)
{
string::size_type c = 0;
while (c != cols)
{
if (r == pad + 1 && c == pad + 1)
{
// We are positioned for the greeting.
cout << greeting;
c += greeting.size();
}
else
{
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
// We are on a border.
cout << "*";
else
cout << " ";
++c;
}
}
cout << endl;
}
return 0;
}
Figure 9: Greeting.3
2 TESTING AND LOOPING 23
***********************
* *
* Hello, Wilberforce! *
* *
***********************
Figure 10: A dialogue with Greeting.3
Without the comment, the meaning of pad would not be obvious, although it is not hard to guess
its meaning by reading the next few lines of code. But any comment that is provided to explain the
role of a variable raises an immediate question: could we eliminate the need for the comment by
choosing a better name?
In this case, we could replace pad by spaceAroundGreeting, or some such name. Then the
comment would be unnecessary.
Of course, it takes longer to type spaceAroundGreeting than pad. But the time programmers
take to type a name a few times (five times for this program) is negligible compared to the time
maintainers take to figure out what they meant.
Although there is a comment explaining the meaning of pad, there is no comment explaining the
formulas pad * 2 + 3 and pad * 2 + 2. Again, we can excuse the authors in this case,
because the explanation appears in the book (Koenig and Moo 2000, page 18–22). In production
code, however, these numbers should be accompanied by explanatory comments or even defined
as constants.
We could write the definitions in a way that shows how the values are obtained. This requires more
typing but should not make any difference to the compiled code:
Why does the program use int as the type of rows — which seems quite natural — and the curious
expression string::size_type as the type of cols? This type is used because it is the type
returned by the function string::size(). It is an integer type, but we don’t know which one
(probably unsigned long but possibly something else). If we declare const int cols, the
compiler issues a warning:
2 TESTING AND LOOPING 24
We don’t want warning messages when we compile, and one way to get rid of this message is to use
the correct type.
If the compiler issues warning errors, revise your code until they disappear.
It is not always easy to eliminate warnings, but the effort is worthwhile. If it doesn’t save your time
now, it may save a maintainer’s time later.
2.5 Counting
In everyday life, if we have N objects and want to identify them by numbers, we assign the numbers
1, 2, 3, . . . , N to them. Another way to look at this is to say that the set of numbers forms a closed
interval which we can write as either 1 ≤ i ≤ N or [1, N].
Programmers are different. Given N objects, they number them 0, 1, 2, . . . , N−1. This set of numbers
forms a semi-closed (or semi-open interval which we can write as either 0 ≤ i < N or [0, N). The
advantages of semi-closed intervals include:
0 1 2 3 4 5
0 1 2 3 4 5 6
• The closed interval [M, N] has N − M + 1 elements; the semi-closed interval [M, N) has N − M
elements, which is easier to remember and calculate.
to
[A, B − 1], [B, C − 1], [C, D − 1], . . .
2 TESTING AND LOOPING 25
• The index of the first element of an array A in C++ is 0. The address of the I’th element of the
array is &A + sI where &A is the address of the array and s is the size of one element.
Note that, in the first case, N is the last element processed but, in the second case, N is the first ele-
ment not processed. In fact, we will see later that there are good reasons for writing the termination
condition as != rather than <=:
Start a range with the index of the first item to be processed; end the range with
the index of the first item not processed. The first index of a range is often 0.
We discuss the design of loops with the assumption that they are going to be while loops. If they
later turn out to have the appropriate pattern, we can convert them to for loops. With experience,
we learn to recognize loops that have the for-loop pattern in advance and avoid the conversion
step.
We design while loops using the following schema (the numbers are for reference, not part of the
code):
1 hinitializei
2 // I
3 while (C)
4 {
5 // I ∧ C
6 hbodyi
7 // I
8 }
9 // I ∧ ¬ C
• The comment on line 2 says that, after initialization, the condition I is true. I is the invariant
of the loop.
• The comment on line 5 says that, at the start of the body of the loop, the loop invariant I and
the loop condition C are both true. This provides an assumption that we can use in coding
the loop.
2 TESTING AND LOOPING 26
• The comment on line 7 says that, after the body of the loop has been executed, the invariant
I is still true (this is what being an invariant means).
• The comment on line 9 says that, when the loop exits, the invariant I is true but the loop
condition C is false.
As a simple example of loop design, we consider the problem of writing rows lines of output, as
in Figure 9. We use a counter r to count the number of lines written and, following the convention
for initializing counter, we will initialize it to zero. We will make the minor change of writing ROWS
rather than rows, to improve readability.
Here is a suitable invariant: r lines have been written. Note that initializing r to zero makes the
invariant true, because we haven’t written any lines yet.
If we have printed ROWS lines, there is no more to do. Consequently, the condition for the while
loop is r != ROWS and the code begins:
1 int r = 0;
2 // r lines have been written
3 while (r != ROWS)
4 {
5 // r lines have been written and r != ROWS
The body of the loop must generate one line of output. We don’t care (for this exercise) what
that output will be, so we will just write a cout statement. The body must also count the lines
produced. Thus the code continues:
Line 6 generates one line of output. This invalidates the invariant, as the comment on line 6.1
shows. Incrementing r makes the invariant valid again. We note that an invariant is not always
true, but is true at certain well-defined points in the program. Also, whenever we perform an action
that invalidates the invariant, we must perform another action (++r in this case) that makes it valid
again.
Line 9 can be simplified as follows:
• If we had written the while condition as r < ROWS, this reasoning would lead to a different
conclusion:
That is, we could claim only that the code generates at least ROWS lines of output. This is
correct, but it is less precise than the original conclusion, which is that the code generates
exactly ROWS lines of output. One advantage of != over < as a while condition is that it
gives us a more precise conclusion. (This advantage was first pointed out by Dijkstra (1976,
Note on page 56). We will discuss other advantages later, in connection with the STL.)
• This is an example of the situation mentioned above: the final code matches the pattern of
the for statement and we can write the solution with a for loop. The invariant still applies:
• In addition to the invariant, which expresses something that does not change, we need some-
thing in the loop body that does change. Otherwise, the loop condition would never be satis-
fied and the loop would never terminate. In this example, the thing that changes is obviously
the row counter; in other cases, it might not be so obvious.
• Suppose that we start counting from 1. A plausible invariant is: “r is the next line to be
written”, but this turns out not to be an invariant, because it is not true after we have written
the last line. An invariant that works is “r-1 lines have been written”, which yields the
following code:
1 int r = 1;
2 // r-1 lines have been written
3 while (r <= ROWS)
4 {
5 // r-1 lines have been written and r <= ROWS
6 cout << .... << endl;
6.1 // r lines have been written
6.2 ++r;
7 // r-1 lines have been written
8 }
9 // r-1 lines have been written and not (r <= ROWS)
This is correct, but it is more complicated and error-prone than the solution that counts from
zero. As previously mentioned, the last line implies only that at least ROWS lines have been
written rather than exactly ROWS lines have been written.
2 TESTING AND LOOPING 28
Suppose that f is a continuous real-valued function, A < B, and f (A) ≤ 0 and f (B) > 0. Then a
fundamental theorem of analysis says that there must be a value of x such that f (x) = 0 and A ≤ x <
B; that is, a root (or zero) of f . Using the bisection method, we find a sequence of approximations
to x by halving the interval [A, B) yielding smaller intervals [a, b). Figure 12 illustrates the process.
b3 b2 b1 b0
y=0
a0 a1
Part of the invariant is f (a) ≤ 0 ∧ f (b) > 0. This ensures that there is a root of f in [a, b). To be
complete, we will also require a < b. We cannot expect to find the root exactly, so we will stop when
the interval is sufficiently small; specifically, when b − a < ε. This suggests that the loop condition
should be ¬(b − a < ε), which is equivalent to b − a ≥ ε. Thus we have:
double a = A;
double b = B;
// I ≡ f (a) ≤ 0 ∧ f (b) > 0 ∧ a < b
while (b - a >= eps)
....
// I ∧ b − a < ε
Note that the final comment, obtained by and’ing the invariant and the negation of the while
condition, is what we need: there is a root within a small interval.
To complete the loop body, we find the midpoint of the interval [a, b), which is at m = (b − a)/2. If
f (m) > 0, there must be a root between a and m. If f (m) ≤ 0, there must be a root between m and
b. We can write the code below. Note carefully how the if statement maintains the invariant.
2 TESTING AND LOOPING 29
double a = A;
double b = B;
// I ≡ f (a) ≤ 0 ∧ f (b) > 0 ∧ a < b
while (b - a >= tol)
{
double m = 0.5 * (a + b);
if (f(m) > 0)
b = m;
else
a = m;
// I
}
// I ∧ b − a < ε
Figure 13 on page 30 expands this idea into a complete function and a test program. When this
program is run, it displays:
pi = 3.14159
e = 2.71828
Assertion failed: a < b && f(a) <= 0 && f(b) > 0 &&
"solve: precondition violation",
file f:\courses\comp6441\src\bisect\bisect.cpp, line 13
The following problem arises in pattern recognition: find the maximum contiguous subvector of a
one-dimensional vector (see (Bentley 1986, pp. 69–80)). The problem is trivial if all of the values
in the vector are positive, because the maximum subvector is just the whole vector. If some of the
values are negative, the problem is interesting. For example, given the vector
31 − 41 59 26 − 53 58 97 − 93 − 23 84
59 26 − 53 58 97
We assume that an empty subvector has sum 0. This means that the maximum subvector can never
be negative, because any empty subvector would be larger than that.
There is an obvious solution: we can simply sum all possible subvectors and note which one has
the largest sum. We assume that the given vector has N elements. We need three nested loops: one
to choose the first element of the subvector, one to choose the last element, and one to sum the
elements in between. Figure 14 shows a solution absed on this idea.
The algorithm of Figure 14 has complexity O(N 3).3 It is not efficient and, by inspecting it carefully,
we can see how to do better. During each cycle of the outer loop, we can use a single loop to sum all
subvectors starting at that point. This gives the second version of the algorithm, with two nested
loops and complexity O(N 2), shown in Figure 15.
3
Section 2.8 explains the notation O(N 3).
2 TESTING AND LOOPING 30
#include <iostream>
#include <cassert>
#include <cmath>
double bisect(
double f(double),
double a,
double b,
double tol = 1e-6 )
{
if (a > b)
return bisect(f, b, a, tol);
double logm(double x)
{
return log(x) - 1;
}
int main()
{
cout << "pi = " << 0.5 * bisect(sin, 4, 8) << endl;
cout << "e = " << bisect(logm, 0.5, 3) << endl;
cout << "e = " << bisect(logm, 3, 3) << endl;
}
int maxSoFar = 0;
for (int i = 0; i < N; ++i)
{
for (int k = i; k < N; ++k)
{
int sum = 0;
for (int j = i; j <= k; ++j)
sum += v[j];
maxSoFar = max(maxSoFar, sum);
}
}
int maxSoFar = 0;
for (int i = 0; i < N; ++i)
{
int sum = 0;
for (int j = i; j < N; ++j)
{
sum += v[j];
maxSoFar = max(maxSoFar, sum);
}
}
Many, perhaps most, programmers would give up at this point and simply assume that quadratic
complexity is the best that can be achieved. But, being more persistent, we will seek a better
solution using invariants.
Here is a useful, general technique for solving problems with one-dimensional vectors: process
the vector one element at a time, maintaining and updating as much information as is needed to
proceed to the next step. Specifically, suppose we are about to process element i. What useful
information can we obtain?
The first point to notice is that if we have a subvector “ending here”, we can update it simply by
adding v[i] to it. This will give us a new subvector “ending here” that we can keep if it is bigger
than anything we have already seen.
The second point to notice is that we can remember the value of the largest subvector seen “so far”
(this corresponds to what “we have already seen” in the previous sentence). The invariant that we
need is:
To make the invariant true initially, we set both variables to zero. When we examine v[i], we
note that maxEndingHere will not get smaller if v[i] > 0. Figure 16 shows the final version
2 TESTING AND LOOPING 32
of the algorithm. This version requires time proportional to the length of the sequence. This is
much better than the first version, which required time proportional to the cube of the length of
the sequence.
int maxSoFar = 0;
int maxEndingHere = 0;
for (int i = 0; i < N; ++i)
{
maxEndingHere = max(maxEndingHere + v[i], 0);
maxSoFar = max(maxSoFar, maxEndingHere);
}
2.7 Assertions
As with most programming constructs, there are three things that are useful to know about asser-
tions: syntax (what do we write?); semantics (what happens?); and pragmatics (when and why do
we use assertions?).
Syntax Any code unit that uses assertions must contain either the new-style directive
#include <cassert>
#include <assert.h>
assert( hconditioni );
Semantics
• If the hconditioni yields true, or anything equivalent to true, the assert statement has
no effect.
• If the hconditioni yields false, or anything equivalent to false (i.e., any kind of zero), the
program is terminated with an error message.
The precise form of the error message depends on the compiler. In general, it will contain the text
of the hconditioni, the name of the file in which the assert statement occurs, and the line number
of the statement within the file.
2 TESTING AND LOOPING 33
Think of assert(C) as saying “I (the programmer) believe that C should always be true at this
point in the program”. Then the failure of an assertion implies that the programmer’s belief was
mistaken, which further implies that there was something wrong with the reasoning and therefore
something wrong with the program.
• An invariant is a condition that should be true at certain, well-defined points in the program.
For example, a loop invariant.
A useful trick for assertions is to append “&& hstringi” to the condition, in which hstringi describes
what has gone wrong. This does not change the value of the condition, because a non-empty string
is considered to be true, but it may improve the diagnostic issued by the compiler.
Assertion failed: a < b && f(a) <= 0 && f(b) > 0 &&
"solve: precondition violation",
file f:\courses\comp6441\src\bisect\bisect.cpp, line 13
2.8 Oh Notation
It is useful to have a concise way of describing how long a program or algorithm takes to run. The
conventional way of doing this is to use “big-oh” notation.
The time taken to compute something usually depends on the size of the input. We will use n to
stand, in a general way, for this size. For example, n might be the number of characters to be read,
or the number of nodes of a graph to be processed. If the time required is independent of n, we
say that the time complexity is O(1). If the time required increases linearly with n, we say that the
complexity is O(n).
if and only if there are constants A and M such that, for all N > M, g(N) < A f (N).
Big-oh notation does two things: it singles out the dominant term of a complicated expression, and
it ignores constant factors. For example,
n2 ∈ O(n2)
and 1000000n2 ∈ O(n2)
because, for large enough n, the first term dominates the others. By similar reasoning
n + 10−10n2 ∈ O(n2)
Informally, we don’t say “is a member of O(n2)” but, less precisely, “the complexity is O(n2)” (or
whatever the complexity actually is).
Figure 17 shows a small part of the complexity hierarchy. Each lines defines a set of functions that
is a proper subset of the set defined on the next line. So, for example, O(n) ⊂ O(n log n) (all linear
functions are log-linear), and so on.
Very few algorithms are O(1). We use this set to describe operations that have a constant time
bound. For example, “reading a character” is (or at least should be) O(1). Logarithmic and linear
algorithms are good. Log-linear algorithms are acceptable: sorting, for example, is log-linear4 .
Polynomial algorithms, O(nk) with k > 2, tend to be useful only for small sizes of problem.
Exponential and factorial algorithms are useless except for very small problems. A problem whose
best known solution has exponential or factorial complexity is called intractable. Such problems
must be solved by looking for approximations rather than exact results. On eof the the best-known
intractable problems is TSP: the “travelling salesperson problem”. A salesperson must make a
certain number of visits and the problem is to find an ordering of the visits that minimizes some
quantity, such as cost or distance. The only known way to find an exact solution is to try all possible
4
Provided that you don’t use bubblesort.
2 TESTING AND LOOPING 35
routes and note the minimal route. If n visits are required, the number of possible paths is O(n!),
making the exact solution infeasible if n is in the hundreds or even thousands.
Note that TSP is typical of problem descriptions. We are not really interested at all in travelling
salespersons and, in any case, their actual problems (which might involve 20 visits at most) are
easily solved. But TSP represents the generic problem of finding a minimal path in a weighted
graph, and many practical problems can be put into this abstract form. One example is: find the
quickest path for a drilling machine that has to drill several thousand holes in a printed-circuit
board.
Figure 18 shows the progress that has been made in solving three-dimensional elliptic partial differ-
ential equations. Equations of this kind must be solved for VLSI simulation, oil prediction, reactor
simulation, airfoil simulation, and other significant problems. The difference between O(N 7) and
O(N 3) corresponds to a factor of N 4 , or a million times for a problem for which N = 100.
It is often claimed that hardware has improved more rapidly than software. For some problems,
however, the improvements in software have been just as dramatic as those for hardware. Putting
the two together, a modern supercomputer can solve differential equations more than a trillion
(106 × 106 = 1012) times faster than was possible in 1945.
Figure 18: Solving three-dimensional elliptic partial differential equations (adapted from Numerical
Methods, Software, and Analysis, by John Rice (McGraw-Hill, 1983))
3 BATCHES OF DATA 36
3 Batches of Data
This section covers roughly the same material as Chapter 3 of (Koenig and Moo 2000). However, the
ordering of topics is different and some of the examples are abstracted (for example, we discuss the
mean/median of a general set of numbers rather than student marks) and there is some additional
material (for example, reading from streams other than cin).
The names “Lvalue” and “Rvalue” are derived from the assignment statement
v = e;
Although the assignment looks symmetrical, it is not. When it is executed, the right side, e, must
yield a value and the left side, v, must yield a memory address in which the value of e can be stored.
“Lvalue” and “Rvalue” are quite often written without capitals, as “lvalue” and “rvalue”. We use
initial capitals in these notes for clarity and emphasis.
All Lvalues are Rvalues because, having obtained an address, we can find the Rvalue stored at that
address. But there are Rvalues that are not Lvalues. Lvalues include: simple variables (x); array
components (a[i]); fields of objects (o.f); and a few other more exotic things. Rvalues that are
not Lvalues include literals (for example, 67, "this is a string", true) and expressions.
the list (double x) is a parameter list and x is a parameter. When we call the function, as in
Functions have parameters. When a function is called, arguments are passed to it.
There are a number of ways of passing arguments in C++. Three of them suffice for most appli-
cations. The program in Figure 19 includes examples of these three. When run, it produces the
following output:5
Pass by value: 65
Pass by reference: 66
Pass by constant reference: 55
Pass by value: the parameter is unqualified. For example, double x. When the function is called,
the run-time system makes a copy of the argument and passes the copy to the function. The
function can change the value of its parameter but these changes have no effect in the calling
environment. This explains the output “65”: the function increments its parameter k, but the
argument pbv remains unchanged.
Pass by reference: the parameter is qualified by &, which is read as “reference to”. When the
function is called, the run-time system passes a reference to the argument to the function.
Pass by reference is usually implemented by passing an address. When the parameter is
used in the function body, it is effectively a synonym for the argument. Any change made
to the parameter is also made to the argument. This explains the output “66”: the function
increments its parameter k, and the argument pbr is also incremented.
An argument to be passed by reference must be an Lvalue. The call passByReference(5)
does not compile because 5 is not an Lvalue.
Pass by constant reference: the parameter is qualified by const &, which is read “const reference
to”. The run-time system passes an address, but the compiler ensures that this address is
used only as an Rvalue. Changing the value of the parameter in the function body is not
allowed.
#include <iostream>
void passByValue(int k)
{
++k;
cout << k;
}
int main()
{
cout << "Pass by value: ";
int pbv = 5;
passByValue(pbv);
cout << pbv;
3. Pass by reference.
Pass by reference should be used only when changes made by the function must be passed
back to the caller. The usual way of returning results is to use a return statement. However,
return can return only one value and it is sometimes necessary to return more than one
value. In these and similar situations, reference parameters may be used to return several
items of information.
int main()
{
cout << "Enter observations, terminate with ^D:" << endl;
int obsCount = 0;
double sum = 0;
double observation;
while (cin >> observation)
{
sum += observation;
++obsCount;
}
cout <<
"The mean of " << obsCount <<
" observations is " << sum / obsCount <<
endl;
return 0;
}
Figure 20 shows a program that reads a list of numbers, computes their mean, and displays it. This
is what the console window looks like after running this program:
The character ^D (control–D) is used to indicate the end of an input stream reading from the
keyboard (i.e., cin).
The condition raises two questions: first, why does it work? Second, why do other, seemingly more
natural constructions, not work?
1. The expression cin >> observation returns an updated value of cin. Note that this is
not a boolean value (true or false). This implies that
is equivalent to
2. When cin appears in a condition context, the compiler attempts to convert it into something
that can be considered boolean. By means of a technical trick, this boolean value is true if
the stream is in a “good” state and false if the stream is in a “bad” state.
3. If the stream is in a good state, then the operation cin >> observation must have
succeeded and a value for observation was read successfully.
4. If the stream is in a bad state, the operation failed and the value of observation is unde-
fined.
5. Looking at the way in which while (cin >> observation) is used in the program
above, we see that everything works out nicely: the program either successfully reads a value
and processes it or does not manage to read a value and terminates the loop.
The “technical trick” mentioned in step 2, in case you are interested, is as follows. Since the com-
piler cannot interpret an instance of istream (the class of cin) as a boolean, it looks for a
conversion that would enable it to do so. Class istream provides a conversion from istream
to void*, the type of pointers that point to nothing in particular. If the stream is in a good state,
the result of this conversion is a non-null pointer (probably, but not necessarily, the address of the
stream object), which is considered true. If the stream is in a bad state, the conversion yields a
null pointer, which is zero, and is therefore considered false.
There are several reasons why a stream can get into a bad state. The most likely reason, and the one
we expect here, is that the program has reached the end of the stream (indicated, in this example,
by the ^D key). Another reason is that a disk has failed, although obviously this does not apply to
cin.
The second question we have to answer is: why do other approaches not work? Class stream
provides a predicate6 eof that yields true at the end of the “file” (or, rather, stream). This would
seem to be a natural way of coding the means program:
while (!cin.eof())
{
cin >> observation;
// process observation ....
6
A predicate is a function that returns a boolean. A less formal term is “test”.
3 BATCHES OF DATA 41
This says — or seems to say — “if we are not at the end of the stream, read the next observation,
otherwise terminate the loop”. Unfortunately, it doesn’t work. Here is why.
Suppose that the user enters 2 3 4 ^D, where represents a blank. The program will read the
observations 2, 3, and 4 correctly, and the stream is then positioned in front of the final blank.
It is not at the end of the stream, because there is still a blank character to be read. Therefore,
cin.eof() is false, and the loop continues. The attempt to read another observation fails,
leaving both the stream and the value of observation in an undefined state.
Since testing for end of file before reading is unreliable, we could try testing for end of file after
reading:
while (true)
{
cin >> observation;
if (cin.eof())
break;
// process observation ....
in which the break statement terminates the loop. Unfortunately, this does not work either.
Suppose that the user enters 2 3 4^D, with no blank between the last number and ^D. After
reading “4”, the stream cin is at end of file, cin.eof() returns true, and 4 does not get
processed!
It seems that we must reject eof as being rather useless.7 We are back to using cin as a condition,
after reading:
while (true)
{
cin >> observation;
if (!cin)
break;
// process observation ....
This works, but can be written more concisely in the idiomatic form:
In gneral, the states of an input stream are good, bad, and end of file. These are not mutually
exclusive. If the state is good, it cannot also be either bad or end of file. However, if the state is
bad, it may or may not be end of file. The input statement cin >> n, where n is an integer, for
example, will put the stream into a bad state if the next character in the stream is not a digit or
“−”. But reading can continue after calling cin.clear() to clear the bad state.
3 BATCHES OF DATA 42
#include <iostream>
#include <fstream>
#include <string>
int main()
{
cout << "Enter file name: ";
string fileName;
cin >> fileName;
ifstream fin(fileName.c_str());
int obsCount = 0;
double sum = 0;
double observation;
while (fin >> observation)
{
sum += observation;
++obsCount;
}
fin.close();
cout <<
"The mean of " << obsCount <<
" observations is " << sum / obsCount <<
endl;
}
One of the nice features of C++ stream is that they make most kinds of input and output look the
same to the programmer. The program in Figure 21 asks the user for a file name, reads a list of
numbers from the file, and displays the mean. Note the similarities between this program and
Figure 20. Other points of note include:
• The directive “#include <fstream>” is required for any program that uses input or
output files.
• The type ifstream is the type of input streams. The variable fin is an instance of this
type.
• The constructor for ifstream needs a file name. Curiously, it cannot accept the file name
as a string; instead, it requires a C style string, of type const char* . Consequently,
we have to use the conversion function c_str to convert the string to a const char*.
Calling the constructor with a file name has the effect of opening the file.
7
It can be used if we read the stream one character at a time.
3 BATCHES OF DATA 43
• After the file has been opened, we use fin in exactly the same way that we used cin in
Figure 20.
• When the program has finished reading data from the file, it calls fin.close() to close
the stream. This step is not strictly necessary, because the destructor, called at the end of the
scope, would close the stream if it was still open. Nevertheless, it is good practice to explicitly
close a stream that is no longer required by the program.
ifstream fin(fileName.c_str());
ifstream fin;
// ....
fin.open(fileName.c_str());
• Whenever a program tries to open a file for input, there is a possibility that the file does not
exist. As above, we can use the stream object as a boolean to check whether the stream was
opened successfully:
ifstream fin;
fin.open(fileName.c_str());
if (!fin)
{
cerr << "Failed to open " << fileName << endl;
return;
}
Writing is very similar to reading. The class for output files is ofstream. We use the insert
operator << to write data to the file. The methods open and close work in the same way as they
do for input files. Figure 22 shows a very simple program that writes to an output file.
int main()
{
ofstream fout("randomnumbers.txt");
for (int n = 0; n < 50; ++n)
fout << rand() << ’\n’;
fout.close();
return 0;
}
This section provides a brief overview of stream states. For details, consult (Langer and Kreft 1999,
pages 31–35).
The state of the stream is represented by four bits; Figure 23 shows their names and meanings.
Here are some examples of how the bits can get set:
• The program wants to read an integer and the next character in the stream is ’x’. After the
input operation, failbit is set and the stream position is unchanged.
• The program wants to read an integer. The only characters remaining in the file are “white
space” (blanks, tabs, and newlines). After the input operation, failbit and eofbit are
both set and the stream is positioned at end-of-file.
• The program wants to read an integer. The only characters remaining in the file are digits.
After the input operation, eofbit is set and the stream is positioned at end-of-file.
• The program wants to read data from a disk file but the hardware (or operating system)
reports that the disk is unreadble. After the operation, badbit is set and the stream cannot
be used again.
Name Meaning
goodbit The stream is in a “good” state — nothing’s wrong
eofbit The stream is positioned at end-of-file — no more data can be read
failbit An operation failed but recovery is possible
badbit The stream has “lost integrity” and cannot be used any more
Figure 24 shows how to test the stream bits. These functions are members of the stream classes.
For example, if fin is an input file stream, then fin.bad() tests its badbit. There are several
things to note about theses functions:
• The first five return bool values — that is, true or false.
if (!fin)
// failbit is set or badbit is set
else
// file is OK
• operator void*() is called by writing the stream name in a context where an expression
is expected. For example:
3 BATCHES OF DATA 45
if (fin)
// file is OK
else
// failbit is set or badbit is set
Function Value/Effect
bool good() None of the error flags are set
bool eof() eofbit is set
bool fail() failbit is set or badbit is set
bool bad() badbit is set
bool operator!() failbit is set or badbit is set
operator void*() Null pointer if fail() and non-null pointer otherwise
void clear() Set goodbit and clear the error bits
Output streams use the same state bits, but it is not often necessary to use them. An output stream
is always positioned at end of file, ready for the next write. Output operations fail only when
something unsual happens, such as a disk filling up with data.
The stream class hierarchy is quite large. For practical purposes, there are four useful kinds of
stream:
We will discuss string streams later. For each of these kinds of stream, there is another with “w” in
front (for example, wifstream). These are streams of “wide” (16–bit or Unicode) characters.
File streams are opened by providing a file or path name. The name can be passed to the constructor
or to the open method. When a file is no longer needed, the close method should be called to
close it.
3 BATCHES OF DATA 46
The extract operator >> reads date from an input file. The insert operator << writes data to an
output file. The right operand of an extractor must be a Lvalue. The right operand of an inserter is
an Rvalue.
The right operand of an extractor or inserter may also be a manipulator. Manipulators may extract
or insert data, but they are usually used to control the state of the stream. We have already seen
endl, which writes a new line and then flushes the buffer of an output stream.
Although endl is defined in iostream, most other manipulators are not. They are defined in
iomanip and so we have to write #include <iomanip> in order to use them. Here is a
selection of commonly used manipulators for output streams:
setprecision(n): Put n digits after the decimal point for float and double data
fixed: Use fixed-point format for float and double data (for example, 3.1415926535)
scientific: Use “scientific” format for float and double data (for example, 1.3e12)
Alice 41 1169699.780
Boris 6500 3014133.560
Ching 1478 7915503.960
Daoust 4464 1605672.250
For a few applications, such as computing an average, it is sufficient to read values; we do not have
to store them. For most applications, it is useful or necessary to store values as we read them. The
program in Figure 26 shows one way of doing this.
vector<double> observations;
#include <vector>
3 BATCHES OF DATA 47
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
int main()
{
vector<string> names;
names.push_back("Alice");
names.push_back("Boris");
names.push_back("Ching");
names.push_back("Daoust");
The relation between a generic class and an instantiated class is analogous to the relation between
a function and a function application:
Generic Application
There are various things we can do with a vector. The operation v.push_back(x) inserts the value
x at the back end of the vector v. We do not have to specify the initial size of the vector, and we
do not have to worry about how much stuff we put into it; storage is allocated automatically as the
vector grows to the required size.
The argument for push_back is passed by value. This means that the vector gets its own copy of
the argument, which is usually what we want.
3 BATCHES OF DATA 48
int main()
{
cout << "Enter file name: ";
string fileName;
cin >> fileName;
ifstream fin(fileName.c_str());
vector<double> observations;
double obs;
for ( vector<double>::size_type i = 0;
i != observations.size();
++i )
cout << observations[i] << ’\n’;
}
The method size returns the number of elements in the vector. As with string, the type of
the size is not int but vector<double>::size_type. This is the type that we use for the
controlled variable i in the final for loop of the program.
A vector can be subscripted, like an array. If v is a vector, v[i] is the i’th element. In the program,
observations[i] gives the i’th element of the vector of observations.
This means that, when we write observations[20], for example, there is no check that this
element exists. If it doesn’t exist, the result will be garbage. Even worse, if we use this expression
on the left of an assignment, we can write into any part of memory!
In this example, the language was Algol 60 and the computer was an Elliott 503. The 503 weighed
several tons, had 8K words of memory, and needed 7 µsec to add two numbers.8
Another 25 years have passed, and it is more than 40 years since Hoare’s customers wanted sub-
script checking. Today’s computers are around 10,000 times faster than the 503, and programmers
are still concerned about the time taken to check subscripts. A high proportion of viruses, worms,
phishers, and other kinds of malicious software exploit precisely this loophole.
</sermon>
Fortunately, there are safer ways of accessing the elements of a vector than using subscripting.
One way is to use the function at. The call array.at(i) has the same effect as array[i] but
checks that the index is within range and throws an exception otherwise.
Iterators are another alternative to subscripts and, in many cases, a better one. An iterator is an
object that keeps track of the objects in a container and provides facilities for accessing them. The
type of the iterator that we need is
vector<double>::const_iterator
Two of its values are observations.begin(), which refers to the first element of the
vector observations, and observations.end(), which refers to the first element
not in the vector — that is, one past the end. Iterators have increment (++) and decrement (--)
operators. Iterators also have pointer-like behaviour: dereferencing an iterator yields an element of
the container.
Putting all these things together, we can write the following loop to access the elements in the
vector observations:
This code has two significant advantages over the original version:
• Using the iterator and, specifically, the function end, ensures that we access exactly the
elements that are stored.
list<double> observations;
....
for ( list<double>::const_iterator i = observations.begin();
....
3 BATCHES OF DATA 50
the program compiles and runs with exactly the same effect.
However, if we replace != in by <, the compiler complains — see Figure 27. The compiler actually
produces 22 messages of this form; only the first three are shown here. The problem is that list
iterators, unlike vector iterators, provide equality (== and !=) but not ordering (<, etc.).
In this case, the compiler diagnostic starts with bool std::operator < and, since introduc-
ing < was the only change we made to the program, it is not hard to figure out that it is this operator
that caused the problem. Unfortunately, the STL can produce even worse error messages that can
be very hard to interpret.9
Sorting the vector of observations is very easy. Only one extra line of code is required:
sort(observations.begin(), observations.end());
8
http://members.iinet.net.au/∼daveb/history.html.
9
Some programmers write perl scripts to parse compiler diagnostics and pick out the key parts.
3 BATCHES OF DATA 51
However, sort is not a part of vector; it is one of the algorithms provided by the STL. Conse-
quently, we also need the directive
#include <algorithm>
The STL provides containers, iterators, algorithms, function objects, and adaptors.
Containers are data structures used to store collections of data of a particular type. The operations
available for a container, and the efficiency of the operations, depend on the underlying data
structure. For example, vector provides array-like behaviour: elements can be accessed
randomly, but inserting or deleting elements may be expensive. In contrast, a list can be
accessed sequentially but not randomly, and provides efficient insertion and deletion.
The containers also include set for unordered data and map for key/value pairs without
duplicates. The containers multiset and multimap are similar but allow duplicates.
Iterators provide access to the elements stored in containers. They are used to traverse containers
(i.e., visit each element in turn) and to specify ranges (i.e., groups of consecutive elements in
a container).
Algorithms provide standard operations on containers. There are algorithms for finding, search-
ing, copying, swapping, sorting, and many other applications.
Function objects are objects that behave as functions. Function objects are needed in the STL
because the compiler can sometimes select an appropriate object in a context where it could
not select an appropriate function. However, there are also other uses of function objects.
Adaptors allow interface modification and increase the flexibility of the STL. Suppose we want
a stack. There are several ways to implement a stack: we could use a vector, or a list, or
some other type. The STL might provide a class for each combination (StackVector,
StackList) and perhaps Stack as a default.
In fact, the STL separates abstract data types (such as stack) and representations (such as
vector and list) and provides adaptors to fit them together. Thus we have:
Assuming that the STL provides M container classes and N algorithms, it is tempting to assume
that there are M × N ways of using it, because we should be able to apply each algorithm to each
container. However, this is not in fact how the STL works. Instead:
• A container/algorithm combination works only if the algorithm is appropriate for the data
structure used by the container.
3 BATCHES OF DATA 52
• If the combination does work, its performance is guaranteed in terms of a complexity class,
e.g., O(N).
We have already seen an example of this in Section 3.5. Suppose that i and j are iterators for
a container and that *i and *j are the corresponding elements. We would expect == and !=
to be defined for the iterators. It is also reasonable to expect ++, because iterators are supposed
to proved a way of stepping through the container. But what does i < j mean? Presumably,
something like “*i appears before *j in the container”. This is easy to evaluate if the container is
a vector, because vectors are indexed by integers (or perhaps pointers), which can be compared.
But evaluating i < j for a linked list is inefficient, because it requires traversing the list. This is
why the iterator for a vector provides < but the iterator for list does not.
It is important to check that the algorithm you want to use works with the container that you are
using. The penalty for not checking is weird error messages. For example,
void main()
{
std::vector<int> v;
std::stable_sort(v.begin(), v.end());
}
void main()
{
std::list<int> v;
std::stable_sort(v.begin(), v.end());
}
Why doesn’t the STL generate more useful diagnostics? The reason is that it is based on templates.
The compiler first expands all template applications and then tries to compile the resulting code.
If the code contains errors, the compiler cannot trace back to the origin of those errors, saying
perhaps “list does not provide stable_sort”, but can only report problems with the code
that it has.
3 BATCHES OF DATA 53
Various objects and values associated with containers have types. These types may depend on the
type of the elements for the container. For example, the type of an iterator for vector<int>
may not be the same as the type of an iterator for vector<double>. Consequently, the con-
tainer classes must provide the types we need. In fact, we have already seen expressions such as
vector<double>::const_iterator, which is the type of const iterators for a vector of
doubles.
These type names can get quite long. It is common practice to use typedef directives to abbrevi-
ate them. A typedef has the form
and defines hidentifieri to be a synonym for htype expressioni. For example, after
The program developed in this section is similar, but not identical, to the grading program de-
scribed in Chapter 4 of (Koenig and Moo 2000).
Problem Statement: The program reads a file of marks (e.g., Figure 28) and writes a
report of grades (e.g., Figure 29). Each line of the marks file consists of a name, a
mark for the midterm, a mark for the final, and marks for assignments. The number
of assignments is not fixed; students do as many as they want to. The name is a single
name with no embedded blanks.
A line of the output file is similar to a line of the input file, but the first number is the
total mark, computed as 20% of the midterm mark plus 60% of the final mark plus the
median of the assignments. The output is written twice, once sorted by name, and once
sorted by total mark.
Thomas 47 83 9 8 4 7 6 9 8
Georges 36 88 8 6 7 4 9 7 8 7
Tien 49 91 9 6 7 8 5 6 7
Lei 41 82 8 8 8 8
Oanh 45 76 9 9 8 9 9 8 8 9
Lazybones 31 45
Mohamad 39 99 8 6 7 9 5 6 9
Jane 36 64 7 5 8
Figure 28: Input for grading program
Figure 30 shows the main program. A goal of the design is to use an object to store a student record
and to put as much problem-specific information as possible into the corresponding class.
The first paragraph of the program asks the user for a file name and tries to open the file. The
second paragraph declares the principal data object of the program, a vector of Students. From
this paragraph, we can tell that the Student class must provide a reading capability (>>) and a
method process to compute the final mark.
The last part of the program opens an output file and writes the data to it twice, first sorted by
name and then sorted by total marks. From this section, we deduce that the Student class must
provide two sorting functions, ltNames and ltMarks. We also need a free function showClass
to write the class list.
4 APPLICATION: GRADING A CLASS 55
Sorted by name:
Georges 67.5 36 88 8 6 7 4 9 7 8 7
Jane 52.6 36 64 7 5 8
Lazybones 33.2 31 45
Lei 65.4 41 82 8 8 8 8
Mohamad 74.2 39 99 8 6 7 9 5 6 9
Oanh 63.6 45 76 9 9 8 9 9 8 8 9
Thomas 67.2 47 83 9 8 4 7 6 9 8
Tien 71.4 49 91 9 6 7 8 5 6 7
Sorted by marks:
Lazybones 33.2 31 45
Jane 52.6 36 64 7 5 8
Oanh 63.6 45 76 9 9 8 9 9 8 8 9
Lei 65.4 41 82 8 8 8 8
Thomas 67.2 47 83 9 8 4 7 6 9 8
Georges 67.5 36 88 8 6 7 4 9 7 8 7
Tien 71.4 49 91 9 6 7 8 5 6 7
Mohamad 74.2 39 99 8 6 7 9 5 6 9
Figure 29: Output from grading program
The function showClass is straightforward; it is shown in Figure 31. The output stream os is
passed by reference because the function will change it when writing. The student data is passed
by constant reference because it will not be changed by the function. It uses an iterator to traverse
the vector of marks data, and it requires class Student to provide an inserter (<<).
Figure 32 shows the declaration for class Student. There are several points to note:
• In C++, the declaration of a class and the definitions of its functions are separate. The function
definitions may be — and often are — in a different file.
• A class declaration may introduce functions as friends. Although these functions are not
member functions, they have access to the classes’ private data.
• The declarations public and private introduce a group of declarations with the given
accessibility.
• Functions declared within a class are called member functions. Functions declared outside a
class are called free functions.10 Member functions can be called only with an object, as in
obj.fun().
• There is no constructor. We rely on the default constructor provided by the compiler; this
constructor allocates space for the object but performs no other initialization. When we
define a new instance of Student, we must ensure that all fields are correctly initialized.
10
Strictly speaking, Java does not have free functions. However, classes such as Math provide static functions that
are effectively the same as free functions. In Java, you write Math.sqrt(x), in C++, you write sqrt(x).
4 APPLICATION: GRADING A CLASS 56
int main()
{
string classFileName;
cout << "Please enter class file name: ";
cin >> classFileName;
ifstream ifs(classFileName.c_str());
if (!ifs)
{
cerr << "Failed to open " << classFileName << endl;
return 1;
}
vector<Student> classData;
Student stud;
while (ifs >> stud)
{
stud.process();
classData.push_back(stud);
}
ofstream ofs("grades.txt");
sort(classData.begin(), classData.end(), ltNames);
ofs << "Sorted by name:\n";
showClass(ofs, classData);
class Student
{
friend ostream & operator<<(ostream & os, const Student & stud);
friend istream & operator>>(istream & is, Student & stud);
friend bool ltNames(const Student & left, const Student & right);
friend bool ltMarks(const Student & left, const Student & right);
public:
void process();
private:
static string::size_type maxNameLen;
string name;
int midterm;
int final;
vector<int> assignments;
double total;
};
• There is only one public method, process, which performs any necessary computation on
the data read from the marks file.
• The private data includes the information that is read from the marks file (name, midterm,
final, and assignments) and computed information, total.
• For formatting the output, we need to know the length of the longest name. This is an
attribute of the class, not the object, and so it is declared as a static data member.
• We need methods for input (>>) and output (<<); these are declared as friends.
• We need comparison functions that will be used for sorting: ltNames orders by student’s
names, and ltMarks orders by student’s total marks.
There is an important design choice here. The four friend friend functions cannot be
member functions, because of the way they are called. The alternatives are either to provide
access functions to private data in the class or to declare these functions as friends. Access
functions should be avoided if possible, especially functions with write access, as would be
required for >>. Although friend functions should be avoided too, in this case they provide
better encapsulation.
The next step is to complete the implementation of class Student by providing definitions for
functions and initial values for static variables. The static data member must be initialized like this:
string::size_type Student::maxNameLen = 0;
This is the only way to initialize a static data member. It has the form of a declaration rather than
an assignment (the type is included) and it appears at global scope, that is, outside any function.
4 APPLICATION: GRADING A CLASS 58
The public function process has two tasks: it maintains the length of the longest name seen so
far and it calculates the total mark. Calculating the total mark requires finding the median of the
assignments. The median is meaningless for an empty vector, and the median function requires
a non-empty vector as its argument (see Figure 34). Thus process, shown in Figure 33, calls
median only if the student has done at least one assignment.
void Student::process()
{
if (maxNameLen < name.size())
maxNameLen = name.size();
total = 0.2 * midterm + 0.6 * final;
if (assignments.size() > 0)
total += median(assignments);
}
In general a function should not perform two unrelated tasks, as process does. The rationale in
this case is that process performs all of the processing that is needed for one student record.
There might be more tasks to perform than just these two. An alternative would be to define two
functions, one to update maxNameLen and the other to calculate total. These two functions
would always be called together, so it makes sense to combine them into a single function.
As a general principle, it should always be possible to explain the purpose of a function with a
one-line description. If you need three sentences to say what a function does, there’s probably
something wrong with it. We could describe the purpose of function process as “perform all
calculations needed to generate the marks file”.
The median calculation is performed by the function in Figure 34. The main design issue for this
function is how to pass the vector of scores. Since we have to sort the vector in order to find the
median, we cannot pass it by constant reference. If we pass it by reference, the caller will get back
a sorted vector. Although this does not matter much for this program, a function should not in
general change the data it is given unless the caller needs the changed value. Consequently, we
choose to pass the vector by value, incurring the cost of copying it. Finally, note that median has
a precondition: it does not accept an empty vector. Since its only use in this program is in the
context
if (assignments.size() > 0)
total += median(assignments);
Figure 35 shows the comparison functions that we need for sorting. The parameter lists of these
functions are determined by the requirements of the sort algorithm: there must be two parame-
ters of the same type, both passed by constant reference. Since we have declared these functions
4 APPLICATION: GRADING A CLASS 59
as friends of Student, they have access to Student’s private data members. The type of
name is string and the type of total is double; both of these types provide the comparison
operator <.
After sorting, the records will be arranged in increasing order for the keys. Names will be alpha-
betical: Anne, Bo, Colleen, Dingbat, etc. Records sorted by marks will go from lowest mark
to highest mark. To reverse this order, putting the students with highest marks at the “top” of the
class, all we have to do is change < to >.
The compiler has to perform a number of steps to determine that these functions are called by the
statements
2. The compiler infers from this that the elements to be sorted are of type Student
4 APPLICATION: GRADING A CLASS 60
3. The comparison functions must therefore have parameters of type const & Student
4. There are functions ltNames and ltTypes with parameters of the correct type
Finally, Figure 36 shows the extractor and inserter for class Student. The extractor (input func-
tion, >>) is a bit tricky, because we rely on the failure management of input streams. The key
problem is this: since students complete different numbers of assignments, how do we know when
we have read all the assignments? The method we use depends on what follows the last assignment:
it is either the name of the next student or the end of the file. If we attempt to read assignments as
numbers, either of these will cause reading to fail. Consequently, we can use the following code to
read the assignments:
However, we must not leave the stream in a bad state, because this would prevent anything else
being read. Therefore, when the loop terminates, we call
ifs.clear();
We assume that, if a student name can be read successfully, the rest of the record is also readable.
If the name is not read successfully, the function immediately returns the input stream in a bad
state, telling the user that we have encountered end of file.
What happens if there is a format error in the input? Some markers, although they are asked to
provide integer marks only, include fractions. Suppose that the input file contains this line:
Joe 45 76 9 9 8.5 9 9 8 8 9
Joe 63.6 45 76 9 9 8
.5 15.2 9 9 8 8 9
We see that Joe has lost all his assignment marks after 8.5 and we have a new student named “.5”.
It is clear that, if this was a production program, we would have to do more input validation.
The inserter (output function, <<) does not have these complications. The main points to note are:
• The manipulators:
• We use the longest name to align columns. The type of the variable Student::maxNameLen
is string::size_type but the type expected by setw is std::streamsize. To
avoid warnings from the compiler, we cast the type. Since the cast can be performed at
compile time, we use a static cast:
static_cast<streamsize>(Student::maxNameLen)
In both cases, the function is passed a reference to a stream and returns a reference to a stream. In
fact, of course, both references are to the same stream, but the state of the stream changes during
the operation. The second argument for the extractor is passed by reference, because its value
will be updated when the stream is read. The second argument for the inserter is passed by con-
stant reference, because the inserter should not change it. When writing inserters and extractors,
remember to return the updated stream.
#include <algorithm>
#include <cassert>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
Figure 37: Directives required for the grading program
A C++ program consists of header files and implementation files. The program is compiled as a
collection of translation units. A translation unit normally consists of a single implementation file
that may #include several header files.
Building a program is a process that consists of compiling each translation unit and linking the
resulting object files. A build is the result of building. Some companies have a policy such as “daily
build” to ensure that an application under development can always be compiled and passes basic
tests.
Header files contain declarations but not definitions. This implies that the compiler:
int k;
is read more than once during a build, the linker will complain that k is redefined and will not link
the program. This is why it is important not to put definitions into header files.
Although a header file may be read more than once during a build, a header file should be read
once only during the compilation of a translation unit. Suppose that translation unit A includes
headers for translation units B and C, and these units both include utilities.h. To prevent
the compiler from reading utilities.h twice, we write it in the following way:
#ifndef UTILITIES_H
#define UTILITIES_H
#endif
This is the standard pattern for all header files. You do not have to use the exact name UTILITIES_H,
but it is important to choose a name that is unique and has some obvious connection to the name
of the header file. For example, Accelerated C++ uses GUARD_utilities_h.
Header files generated by VC++.NET contain the directive #pragma once, which has the same
effect.
In most cases, the guards are not logically necessary. Since header files contain only declarations,
reading them more than once should not cause errors. Some header files, however, cannot be read
twice, and these can cause problems if they don’t have guards. A more important reason for using
guards is efficiency: header files can be very long, and they may include other header files. Without
the guards, the compiler may be forced to read thousands of lines of declarations that it has seen
before.
Typically, a header file will contain declarations for types, constants, functions, and classes.
A header file should #include anything that the compiler needs in order to process it. For
example, if a class has a data member of type string, its header file must contain
#include <string>
It is not a good idea to include using declarations in header files. A header file may be included
in many translation units that may not want namespaces opened for them.
Implementation files contain definitions for the objects declared in header files. An implementation
file is processed only once during a build. An implementation file should #include its own header
file and header files for anything else that it needs.
As a general rule, the first #include directive should name the header file corresponding to the
implementation file. For example, utilities.cpp would have the following structure:
4 APPLICATION: GRADING A CLASS 64
#include "utilities.h"
Header and implementation files create dependencies, which are discussed in Section 4.5 below.
A header file may depend on other header files and an implementation file may depend on one or
more header files. A file should never depend on an implementation file; in other words, you should
never write
#include "something.cpp"
When an implementation file #includes header files, the compiler obviously reads all of the files.
Amongst other things, it checks that declarations in header files match definitions in implemen-
tation files. It is important to realize that the checking is not complete. For example, the header
file
#ifndef CONFLICT_H
#define CONFLICT_H
#endif
#include "conflict.h"
#include <vector>
will not produce any error messages. Since C++ allows functions to be overloaded, it assumes
that the two versions of mean are different functions and that the vector version will be declared
somewhere else. If the program calls either version, the linker will produce an error message.
We split the grading program of Section 4.2 into three translation units:
1. class Student
4 APPLICATION: GRADING A CLASS 65
2. function median
The translation unit for function median is rather small, but it demonstrates the idea of splitting
of generally useful functions in a larger application. For a small program such as this one, we could
have put Student and median into the same implementation file.
Figure 38 shows the header file for class Student, student.h. There is an #include directive
for each library type mentioned in the class declaration. The class declaration is unchanged from
the original program.
Although function showClass is not a friend of class Student, it is closely related to the
class; consequently, we put its declaration in student.h.
Figures 39 and 40 show the implementation file for class Student, student.cpp. The first
#include directive includes student.h; this ensures that student.h does not depend on
anything that it does not mention (if it did, the compiler would fail while reading it). Then we in-
clude median.h for this program, and finally the library types that we need. Since student.h
includes iostream, string, and vector, we need only include iomanip for the output state-
ments.
The implementation file student.cpp, shown in Figures 39 and 40 implements the member
function of Student, process, and the friend functions. It also initializes the static data
member maxNameLen.
The header and implementation files for median are both short. In a more typical application,
other useful functions might be incorporated into a single translation unit.
The last step is to write an implementation file for the main program, grader.cpp. We do not
need a header file (which would be called grader.h) because no other translation unit refers to
anything in the main program. It is a good idea in general to avoid dependencies on the main
program.
This translation unit includes only the header files for other translation units that it needs —
student.h in this case — and any library types.
4 APPLICATION: GRADING A CLASS 66
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
#include <vector>
class Student
{
friend std::ostream & operator<<(std::ostream & os,
const Student & stud);
friend std::istream & operator>>(std::istream & is,
Student & stud);
friend bool ltNames(const Student & left, const Student & right);
friend bool ltMarks(const Student & left, const Student & right);
public:
void process();
private:
// Data read from file
std::string name;
int midterm;
int final;
std::vector<int> assignments;
#endif
Figure 38: student.h: header file for class Student
4.5 Dependencies
Figure 44 shows the dependencies between the files of the grading program. Dependencies on
libraries are not shown. File X depends on file Y if the compiler must read Y in order to compile X.
In general:
#include "student.h"
#include "median.h"
#include <iomanip>
string::size_type Student::maxNameLen = 0;
void Student::process()
{
if (maxNameLen < name.size())
maxNameLen = name.size();
total = 0.2 * midterm + 0.6 * final;
if (assignments.size() > 0)
total += median(assignments);
}
Figure 39: student.cpp: implementation file for class Student: first part
4 APPLICATION: GRADING A CLASS 68
Figure 40: student.cpp: implementation file for class Student: second part
#ifndef MEDIAN_H
#define MEDIAN_H
#include <vector>
#endif
Figure 41: median.h: header file for function median
Dependencies have an important effect on compilation time. A file with a high in-degree will trigger
extensive recompilation when it is changed.
In Figure 44, a change to either median.h or student.h will cause two of the three implemen-
tation files to be recompiled. If grader.cpp depended on median.h, changing median.h
would cause all three implementation files to be recompiled.
In a small program like the grader, the effect of dependencies on compilation is negligible. In large
programs, the effect can be significant. Large programs require hours or even days to compile.
Some header files are used by hundreds or even thousands of implementation files. A change to
one of the header files can trigger hours of recompilation time.
An important component of large-scale C++ design is to reduce the dependencies between source
files. We will discuss ways to do this as the course progresses.
4 APPLICATION: GRADING A CLASS 69
#include "median.h"
#include <algorithm>
#include <cassert>
Strings Class string provides a large number of functions in addition to those that we have
already seen. See http://www.cppreference.com/cppstring/all.html for a com-
plete reference.
Operator + concatenates strings. There are several overloads, allowing for all combinations of
char, C strings, and strings. Operator [] provides indexing for strings.
Strings function as containers for characters, working in a very similar way to the type vector<char>.
Consequently, iterators, push_back, and similar functions work for strings. In particular, string
provides insert to insert characters into a string, erase to remove characters from a string, and
replace to replace a sequence of characters in a string.
There several functions for finding characters or substrings in strings: find, find_first_of,
find_first_not_of, find_last_of, and find_last_not_of.
Characters The library cctype provides the same functionality as the C header file ctype.h.
Although many of these functions should now be considered obsolete (e.g., strcpy and friends),
others are still useful. In particular:
#include "student.h"
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
int main()
{
// Attempt to open file provided by user
string classFileName;
cout << "Please enter class file name: ";
cin >> classFileName;
ifstream ifs(classFileName.c_str());
if (!ifs)
{
cerr << "Failed to open " << classFileName << endl;
return 1;
}
// Print reports
ofstream ofs("grades.txt");
sort(classData.begin(), classData.end(), ltNames);
ofs << "Sorted by name:\n";
showClass(ofs, classData);
median.h student.h
tolower(c) returns the lower case equivalent of an upper case character and leaves other char-
acters unchanged
toupper(c) returns the upper case equivalent of an lower case character and leaves other char-
acters unchanged
5 POINTERS AND ITERATORS 72
An important difference between C++ and Java is that, in C++, dynamic memory allocation and
deallocation is explicit (done by code written by programmers) whereas in Java it is implicit (done
by built-in system code). It is not quite true to say “Java does not have pointers”, but it is true to
say “Java does not allow direct access to pointers”.
Like all variables in C++, a pointer has a type. The type depends on the object addressed by the
pointer. For example, a pointer that points to an int has type “pointer to int”, written int*.
To assign a value to a pointer, we need a way of obtaining addresses. There are two common ways,
and we define the unimportant one first. The operator &, applied to a variable, yields the address
of that variable. The address can be stored as a pointer. The following code defines two pointers,
pk1 and pk2, both pointing to the integer k.
int k = 42;
int *pk1 = &k;
int *pk2 = &k;
If we have a pointer to an object, we can obtain the object itself by applying the prefix operator *.
In the example above, *pk1 is an integer variable (it is actually, of course, the integer k).
The declaration int *pk1 is a kind of pun. We can read it as (int *)pk1 (“ pk1 has type
int *”) or as int (*pk1) (“*pk1 has type int”). The forms with parentheses are illegal, but
the C++ compiler is not fussy about spaces: we can write any of
Some programmers prefer the first form and some the second; few use the third, although it is
legal. There is one syntactic trap that you should be aware of. The statement
int *p, q;
Using pointers can have strange results — although they are not all that strange if you think about
them carefully. For example, the code
5 POINTERS AND ITERATORS 73
int k = 42;
int *pk1 = &k;
int *pk2 = &k;
++(*pk1);
cout << k << ’ ’ << *pk2 << endl;
displays 43 43. Since both pointers point to the same integer, any change to its value will be seen
by all pointers.
C++ provides arithmetic operations (+ and −) on pointers. However, the arithmetic is rather special.
If p1 and p2 are pointers and i is an integer, then:
p1 + i is a pointer
p1 - i is a pointer
p1 - p2 is a signed integer (p1 and p2 must have the same type)
These operations would be utterly meaningless if it were not for the fact that C++ uses the size
of the object pointed to when doing arithmetic. For example, suppose that an instance of type T
occupies 20 bytes and that we write:
T t;
T *pt = &t;
This kind of arithmetic is esactly what we need for arrays. In fact, subscript operations in C++ are
defined in terms of pointer arithmetic. The declaration
double a[6];
a[0] ≡ ∗a
a[1] ≡ ∗(a + 1)
a[2] ≡ ∗(a + 2)
...
a[i] ≡ ∗(a + i) for any integer i
Most data in C++, and all the data we have seen so far in this course, is allocated on the run-time
stack.
The run-time stack, “stack” for short, is initially empty. When execution starts, global data is
pushed onto th stack. On entry to a function, the local data associated with the function (including
its arguments) are pushed onto the stack. When the function returns, the local data is popped off
the stack. Thus the stack varies in size as the program runs.
5 POINTERS AND ITERATORS 74
When a function has returned, its local data no longer exists.11 Normally, this is not a problem, be-
cause the function’s local variables are no longer accessible. Playing tricks with pointers, however,
can cause problems. Consider the code shown in Figure 45.
int * f()
{
int k = 42;
int *pk = &k;
return pk;
}
int main()
{
int *p;
p = f();
return 0;
}
This program compiles because there are no syntactic or semantic errors. The final assignment,
p = f(), makes p a pointer to k. But k no longer exists, having been popped off the stack when
f returns. Any attempt to use p will have unpredictable results.
char *read()
{
char buffer[20];
cin >> buffer;
return buffer;
}
int main()
{
char *pc = read();
cout << pc << endl;
return 0;
}
Figure 45 shows a more subtle version of the same problem. The function read has result type
char* but actually returns an array of characters: this works because the compiler treats these
types as the same. Similarly, the main function treats function read as having type char*.
The reason that this is a bad program is that the array buffer is allocated on the stack. It is
destroyed when the function returns. The pointer pc is undefined and cannot be used safely.
11
Actually, it’s still there, on the stack, but will be overwritten when the next function is called. Consequently, we
must assume that it no longer exists.
5 POINTERS AND ITERATORS 75
The compiler12 actually recognizes the mistake and issues a warning message:
f:\Courses\COMP446\src\Pointers\pointers.cpp(24) :
warning C4172: returning address of local variable or temporary
This provides another reason for paying attention to warnings from the compiler!
Problems like this tend to occur when we use “old-style” C++ code. No problems arise if we use the
STL class string instead of an array of characters.
Stack allocation works because function calls and returns match the “last-in-first-out” (LIFO) disci-
pline of a stack. Sometimes this is not good enough. For example, we might want to allocate data
within a function, use that data for a while after the function has returned, and then deallocate the
data. We can do this by allocating the data on the heap, an area of memory that does not obey any
particular discipline such as LIFO or FIFO. The heap is used like this:
T *p = new T();
....
delete p;
The operator new requires a call to a constructor on its right. The value returned by new is a
pointer to the constructed object. We can use this pointer to perform operations on the object.
When we have finished with the object, we apply delete to the pointer to destroy the object and
deallocate the heap memory it was using.
Suppose class T provides a public function f. To call f using the pointer p, we must first derefer-
ence p and the use the “dot” operator to call f. Thus we write (*p).f(). (The parentheses are
necessary, because the compiler reads *p.f() as *(p.f(), which is wrong.) Since this construc-
tion occurs often, there is an abbreviation for it:
p->f() ≡ (*p).f()
Figure 47 provides a simple example of heap allocation and deallocation. The function maketest
constructs a new instance of class Test on the heap, calls its function f, and returns a pointer to
it. The function killTest deletes the object. The program displays the following output:
makeTest
Constructor
Function
killTest
Destructor
12
VC++ 7.1
5 POINTERS AND ITERATORS 76
class Test
{
public:
Test() { cout << "Constructor\n"; }
~Test() { cout << "Destructor\n"; }
void f() { cout << "Function\n"; }
};
Test *makeTest()
{
cout << "makeTest\n";
Test *pt = new Test();
pt->f();
return pt;
}
int main()
{
Test *p = makeTest();
killTest(p);
return 0;
}
The careful reader will have observed that null pointers are represented by 0, rather than NULL, in
the code for the traversal program. This is because NULL presents a problem for C++ programmers.
#define NULL 0
This is compatible with the spirit of C’s rather loose approach to types, but is not consistent with
C++’s safer typing. Improvements such as
do not help, because the first version does not work for pointers and the second version requires
an ugly-looking cast whenever we use NULL for a pointer type other than void*.
In C++, #defines are deprecated, and we are supposed to use constant declarations instead.
Unfortunately, any reasonable declaration of NULL has the same problems as the attempts to
#define NULL:
and call f(NULL) thinking that the compiler would say to itself: “The programmer has used NULL,
which suggests a pointer, and I will therefore pass (char*)NULL to the second overload”.
However, the compiler does not reason like this. Instead, it says: “NULL is 0 and 0 is an int, and I
will therefore pass 0 to the first overload”.
As Meyers (1992, pages 87–89) explains, this is an unusual case because people tend to think that
there is an ambiguity but the compiler does not. (Usually, people think their meaning is perfectly
obvious and are annoyed when the compiler calls it ambiguous.) The morale is:
Prefer not to overload a function with integer types and pointer types.
5.2 Iterators
Iterators are one of the keys to the flexibility of the STL. We have seen that the STL provides con-
tainers and algorithms. Iterators provide the glue that allows us to attach one to the other:
For example, vector<T> provides the kind of iterators that sort requires; it follows that we can
sort vectors.
A pair of iterators specifies a range of container elements. The range typically defines a semi-closed
interval: the first iterator of a range accesses the first element of the range, and the last iterator
accesses the first element not in the range. In this typical loop
5 POINTERS AND ITERATORS 78
hiteratori stands for some iterator type, and we see that the iterator must provide the operations:
C++ programmers will recognize that all of these operations are provided by pointers. In fact, we
can use raw pointers as iterators:
There are several ways of classifying iterators. Below, we define individual properties; most itera-
tors possess several of these properties. In each of the following cases, we use it to stand for an
iterator with the given property. Figure 48 summarizes the properties that various kinds of iterator
provide.
• An input iterator can be used to read elements from a container but does not provide write
access. That is, *it is an rvalue.
5 POINTERS AND ITERATORS 79
• An output iterator can be used to update elements in a container but may not provide read
access. That is, *it is a lvalue.
• A forward iterator is an input and output iterator that can traverse the container in one
direction. A forward iterator must implement ++.
• A bidirectional iterator is an input and output iterator that can traverse the container forwards
and backwards. A bidirectional iterator must implement ++ and --.
There are no “backwards only” iterators; an iterator is either forward or bidirectional.
• A random access iterator must allow “jumps” in access as well as traversal. The principal
operation that a random access must provide is indexing: it[n]. Random access iterators
also provide:
• An insert iterator is an output iterator that puts new values into a container rather than just
updating the values that are already there.
All of the STL containers provide bidirectional iterators. It follows that they all provide input, out-
put, and forward iterators. These categories are useful because we can construct special iterators
that may not have all of the properties.
The only container classes that provide random access iterators are deque, string, and vector.
This is because these containers are required to store elements in consecutive locations, which
means that random access is a simple address calculation.13
We have often mentioned that a range is specified by an iterator accessing the first element of the
range and another iterator accessing the element following the last element of the range — which,
in most cases, does not even exist. Here are some reasons for this choice:
2. We can use == and != to test for an empty range and for end of range — we do not need <
and friends.
3. We have an easy way to indicate “out of range”, namely, the last iterator of the range.
A function can return an iterator for a valid element to indicate success or an iterator for an
invalid element to indicate failure. This avoids the need for special values, flags, etc.
An iterator with type iterator is allowed to change the contents of its associated container.
An iterator with type const_iterator (called a constant iterator) is not allowed to change the
contents of its associated container. It is best to use constant iterators whenever possible.
13
The address of c[i] is &c + s × i, where &c is the address of the container and s is the size of an element.
5 POINTERS AND ITERATORS 80
Suppose that we want to divide the students of the grading program into two groups, according as
to whether they passed or failed the course. The first thing we will need is a criterion for deciding
whether a student has passed. We add the following member function to class Student:
• Its definition appears within the class declaration. This is allowed, and a consequence is that
the compiler may inline calls to the function.
• The const indicates that the function does not change the state of the object. The signifi-
cance of this will emerge shortly.
Let us first consider a straightforward approach, in which we create two empty vectors for passed
and failed students, and iterate through the class assigning each student to one or the other vector:
see Figure 49. In this code, note that it->passed() is an abbreviation for (*it).passed().
vector<Student> passes;
vector<Student> failures;
for ( vector<Student>::const_iterator it = data.begin();
it != data.end();
++it )
if (it->passed())
passes.push_back(*it);
else
failures.push_back(*it);
If we omit the const in the declaration of passed, this code will not compile: see Figure 50. This
is because a const_iterator can only be used with a constant container. Although passed
does not alter the state of a student, the compiler cannot tell this, and will reject Figure 49. By
stating explicitly that passed is a const function, we inform the compiler that the container will
not change and we can use a const_iterator.
The code in Figure 49 would also work if we omitted const from passed and from the iterator
declaration. However, it is good practice to use const wherever it applies, and so Figure 49 is
preferable to code without consts.
After executing the code in Figure 49, we now have three vectors and two copies of each student
record, one in the original vector and the other in either passes or failures. It would be more
efficient in terms of space to move the failed students into a new vector and remove them from
the original vector. Vectors provide the function erase to remove elements from a container. The
code in Figure 51 does this.
5 POINTERS AND ITERATORS 81
f:\....\grader.cpp(111):
error C2662: ’Student::passed’ :
cannot convert ’this’ pointer from
’const std::allocator<_Ty>::value_type’
to ’Student &’
with
[
_Ty=Student
]
vector<Student> failures;
vector<Student>::iterator it = data.begin();
while (it != data.end())
{
if (it->passed())
++it;
else
{
failures.push_back(*it);
it = data.erase(it);
}
}
The first point to note is that we have to use a while loop rather than a for loop, because the
loop step is not necessarily ++it. However, for students that pass the course, ++it is all we have
to do.
When a student fails, the corresponding record is stored in failures. In order to remove the
record from the class data vector, we write
it = data.erase(it);
The effect of data.erase(it) is to remove the element indicated by it from the vector data.
After this has been done, the iterator is invalid because it accesses an element that no longer exists.
The function erase returns an iterator that accesses the next element of the vector.
It is important to use the iterator returned by erase and not to assume that it is just ++it. A
iterator operation that invalidates an iterator may do other things as well, even including moving
the underlying data. When an iterator operation invalidates an iterator, it potentially invalidates all
iterators.
For example, calling erase in Figure 51 invalidates the iterator for the end of the vector, because
removing one component forces the remaining components to move. It would therefore be a serious
mistake to attempt to “optimize” Figure 51 like this:
5 POINTERS AND ITERATORS 82
vector<Student> failures;
vector<Student>::iterator it = data.begin();
vector<Student>::iterator last = data.end(); // Save final iterator
while (it != last)
....
The solution we have developed works correctly, but is inefficient. The inefficiency is negligible for
a class of sixty students but could be a problem if we used the same strategy for very large vectors.
To understand the reason for the inefficiency, suppose that an entire class of 50 students fails. The
program would execute as follows:
To improve the performance, we must change the data structure. A list can erase in constant time
(i.e., O(1)) and can perform the other operations that we require. It is a straightforward exercise to
replace each vector declaration by a corresponding list declaration.
It is obviously important to know which operations invalidate iterators. Fortunately, good STL
reference documents usually provide this information. If you are not sure, you can make a good
guess by thinking about how the operation must work on a given data structure — but it’s much
safer to look up the correct answer.
Most containers have range functions — that is, functions with a pair of parameters representing a
range of elements in the container. If a suitable range function exists, it is better to use it than to
use a loop.
Suppose that you want to create a vector v1 consisting of the back half of the vector v2 (Meyers
2001, Item 5). You could do it with a loop:
v1.clear();
for ( vector<Widget>::const_iterator ci = v2.begin() + v2.size()/2;
ci != v2.end();
++ci )
v1.push_back(*ci);
v1.clear();
copy(v2.begin() + v2.size()/2, v2.end(), back_inserter(v1));
6 Template Programming
Templates enable us to write generic, or parameterized, code. The basic idea is simple but some of
the implications — at least for C++— are subtle.
All of the material in this section is covered in (Koenig and Moo 2000). For a more detailed and
complete description of templates, (Vandervoorde and Josuttis 2003) is recommended.
These functions perform the same task for different types. Since C++ allows overloading, we could
use all three in the same program, but there does appear to be some redundancy.
We can use templates to avoid source code redundancy. We replace the previous three definitions
by the following template function declaration:
The new function can be called in the same way as the previous versions. It is not necessary to
specify the type of the arguments, because the compiler already has this information. The code
14
The name Swap, rather than swap, was chosen to avoid confusion with the standard library function.
6 TEMPLATE PROGRAMMING 85
char c1 = ’a’;
char c2 = ’b’;
Swap(c1, c2);
cout << c1 << ’ ’ << c2 << endl;
int m = 3;
int n = 5;
Swap(m,n);
cout << m << ’ ’ << n << endl;
prints
b a
5 3
To compile the call Swap(c1, c2), the compiler must perform the following steps:
1. Infer the types of the arguments c1 and c2 (in this case: char and char).
5. Generate source code for the function Swap<char> (which should be the same as function
(1) above).
The compiler detects errors in the template code, if there are any, at step 6, when it compiles the
code obtained by expanding the template. This means that errors in template code are reported
only if the template is instantiated. You can write all kinds of rubbish in a template declaration and
the compiler won’t care if you never use the template.
The process of deriving an actual function from a template declaration is often called “instantiating”
the template. This usage is confusing, because we also talk about objects obtained by instantiating
a class. These notes use the expression applying a template or the application of a template, by
analogy with “applying a function”.
Although templates remove redundancy in the source code, they do not affect the object code. If
the program calls Swap with N different argument types, there will be N versions of Swap in the
object code.
The following template function returns the greater of its two arguments.15
15
The name Max is used to avoid confusion with the library function max.
6 TEMPLATE PROGRAMMING 86
We would expect this function to work with various types, and indeed it does. Each of the following
statements compile and execute correctly:
#include <typeinfo>
Executing
displays
and reveals the problem: we cannot compare strings of different lengths because they have different
types. Also, Max is not comparing the strings; it is comparing the addresses of the strings (i.e., the
pointers).
There are no good, general solutions to problems like this. For Max, the best thing to do is to define
a non-template version for strings:
When the compiler encounters Max("apple", "berry"), it will consider the string version
a better match than the template version.
class Widget
{
public:
Widget(int w) : w(w) {}
private:
int w;
};
Max(Widget(1), Widget(2));
It is easy to see what has happened: the compiler has generated the function
and has then discovered that Widget does not implement operator>. The correction is also
straightforward: we just have to add the function
friend bool operator>(const Widget & left, const Widget & right)
{
return left.w > right.w;
}
The use of templates prevents some of the conversions that we expect. If we declare
Max(1.2, 3.4);
Max(1, 3.4);
Max(1, 3);
The first call works because the types match exactly, and the other two calls work because the
compiler includes code to convert 1 and 3 from int to double before the function is called.
With the template version, however, the compiler does not allow the second call. It matches
Max(int,int) and Max(double,double) to the template pattern, but Max(int,double)
does not match and the compiler will not insert conversions to make it match.
There are several ways to make the second call work properly:
6 TEMPLATE PROGRAMMING 89
Max(static_cast<double>(1), 3.4);
Max<double>(1, 3.4);
• We can avoid calls of the form Max(1, 3.4) with mixed-type arguments.
Template parameters are not restricted to types. We can also use integral types (that is, char,
short, int, and long) as parameters. This function has an integer template parameter16
template<int MAX>
int randInt()
{
return rand() % MAX;
}
// Throwing dice
for (int i = 0; i != 20; ++i)
cout << setw(2) << randInt<6>() + 1;
cout << endl;
Classes can be parameterized with templates; the notation is similar to that of function templates.
Here is a simple class for 2D coordinates, in which each coordinate consists of two floats.
class Coordinate
{
public:
Coordinate(float x, float y) : x(x), y(y) {}
void move(float dx, float dy);
private:
float x;
float y;
};
3. — important! — within the declaration, replace occurrences of the class name C by C<T>.
Performing these steps for class Coordinate yields the following declaration:
template<typename T>
class Coordinate
{
public:
Coordinate<T> (T x, T y) : x(x), y(y) {}
void move(T dx, T dy);
private:
T x;
T y;
};
Unlike functions, the compiler cannot infer the argument type for classes. Whenever we create an
application of a template class, we must provide a suitable argument:
The integer argument 5 is acceptable for the Coordinate<float> constructor because the
template application is explicit: the compiler knows that float values are expected, and inserts
the appropriate conversion.
template<typename T>
void Coordinate<T>::move(T dx, T dy)
{
x += dx;
y += dy;
}
In general, if the definition of a member function for a template class uses the template parameter,
we must:
Like functions, template classes can have non-type template parameters, provided that the param-
eters have integral types. Instances of the class must be provided with constant arguments of
appropriate types.
Figure 52 shows part of a template class for vectors. It is parameterized by Type, the type of a
vector element, and Dim, the dimension of the vectors. A typical declaration would be
Vector<double, 3> v;
If the program uses many vectors of this type, we would probably define a special type for them, to
reduce the amount of writing required and improve the clarity of the program:
• There is a default constructor that sets the elements of the vector to zero. The compiler’s
default constructor would leave the elements uninitialized.
• The function operator[] returns a reference to a vector element. This function allows a
user to get or set any element.
It is good practice (as we will discuss later) to provide two versions of this function, one
returning an lvalue (as here) and the other returning an rvalue.
• The function operator[] performs a range check and aborts the program if the range
check fails. It would probably be better to handle a range check error by throwing an excep-
tion.
6 TEMPLATE PROGRAMMING 92
private:
Type v[Dim];
};
• Several of the functions have for-loops for the range [0,Dim). A good compiler might opti-
mize these away for small values of Dim (this optimization is a special case of loop unrolling).
If we were worried about the overhead of a for-loop, we could rewrite the code using if or
switch statements. Figure 53 shows how this might be done for operator+. The code
looks long but, when the compiler expands Vector<double,3>, it will see something like
this:
if (3 == 1)
....
else if (3 == 2)
....
else if (3 == 3)
....
else
Any reasonable compiler should be smart enough to compile the code for the “3 == 3” case
and generate no code for the conditional expressions or the other cases.
<aside> People sometimes wonder why a compiler should bother optimizing code such as
if (1 == 0)
....
on the grounds that no sane programmer would write code like this. Such optimizations are
important, and very common, because a lot of code is not written explicitly by programmers,
but is generated by template expansion, code generators, and in other ways. Unless the
generator is very smart, generated code may be very stupid. </aside>
When we have obtained a type by applying a class template, we can do all of the usual things with
it:
Early versions of C++ with templates used “class” where we have been using “typename”. For
example:
template<class T>
class Coordinate { ....
6 TEMPLATE PROGRAMMING 94
This usage suggested that the argument replacing T had to be a class and could not be a built-in
type, such as int. The keyword typename suggests that any type can be used, including the
built-in types.
6.3 Complications
We have seen that normal practice in C++ programming is to put declarations into header files
and definitions into implementation files. This does not work for templates. The compiler cannot
generate code for a function such as
6 TEMPLATE PROGRAMMING 95
template<typename T>
void Coordinate<T>::move(T dx, T dy)
{
x += dx;
y += dy;
}
without knowing that the argument that replaces T and, if this definition is in an implementation
file, the compiler cannot access it when it compiles a call such as v.move(2,3).
There are several solutions. Different platforms have different policies, but a solution that works
on (almost?) all platforms is to treat any template code, even a function such as move above, as a
declaration.
template<typename T>
T f()
{
return ??
}
Even if we could write a sensible expression after return, the compiler could not deduce the
template argument at the call site.
In general, if the return type of a function is a template parameter, then the function must have at
least one parameter typed with the same template parameter, as in:
template<typename T>
T f(const T & param) { .... }
It is sometimes necessary or desirable, for efficiency or other reasons, to provide a special imple-
mentation for some particular value of the template parameters. Suppose, for example, that we
want to have both a general template class for all kinds of vectors, as above, but we also want to
give special treatment to three-dimensional vectors with double elements. This is called special-
ization. Suppose the original class was
template<typename T>
class Widget
....
6 TEMPLATE PROGRAMMING 96
template<>
class Widget<specType>
....
where specType is the value of T for which we are providing a specialized implementation. In
the rest of the class, we must replace all occurrences of <T> with specType, including changing
Widget<T> to Widget<specType>.
Figure 54 shows the result of specializing the generic vector class for 3D double vectors. The
constructor has been modified with the addition of an output statement to demonstrate that the
specialized version is actually used. The definition
Vector<double,3> v;
3D Vector
Within the declaration of the specialized version, we have unrolled the for-loops and made other
small changes. We could also add functions, such as cross product, that are useful for 3D vectors
but not other vectors.
It is also possible to partially specialize a template class with two or more template parameters. For
example, we could specialize Vector to 3D vectors with any element type. The class declaration
would begin
template<typename Type>
class Vector<Type,3>
....
Within the class declaration, instances of Dim are replaced by 3, but instances of Type are left
unchanged. References to the class all have the form Vector<Type,3>.
Template specialization is the key to template metaprogramming. The following class declaration
is allowed:
template<int N>
class Fac
{
public:
Fac()
{
Fac<N-1> f;
val = N * f.getVal();
}
int getVal() { return val; }
private:
int val;
};
6 TEMPLATE PROGRAMMING 97
template<>
class Vector<double,3>
{
public:
Vector<double,3>()
{
v[0] = 0; v[1] = 0; v[2] = 0;
cout << "3D Vector" << endl;
}
private:
double v[3];
};
However, there is a problem: instantiating Fac<4> requires instantiating Fac<3> requires instan-
tiating . . . . We can terminate the recursion by providing a specialized class Fac<0>, as follows:
template<>
class Fac<0>
{
public:
Fac() : val(1) {}
int getVal() { return val; }
private:
int val;
};
Fac<4> f;
cout << f.getVal() << endl;
The compiler constructs class declarations for Fac<4>, Fac<3>, Fac<2>, Fac<1>, and Fac<0>.
At run-time, executing the constructor for Fac<4> invokes the constructor for Fac<3>, and so
on.
The same is true of template class declarations. For example, if we changed the declaration of
Vector in Figure 52 to
and defined
Vector<int> u;
Vector<> v;
Vector v;
is not allowed. The brackets <> are required even when we are using the default values of all
parameters. (The same is true for functions, of course.)
6 TEMPLATE PROGRAMMING 99
In this section, we discuss an example built on the following observation: we can define a general
traversal routine for a tree using a generic store, and then specialize the traversal by providing
different kinds of store.
For simplicity, we will use binary trees, although the technique can be extended to general trees
and graphs. Figure 55 shows pseudocode for the general traversal. In this pseudocode, we assume
that we are given the root of a binary tree and an empty store. The store provides operations
put and get, and a test empty. The order of the traversal is determined by the behaviour of the
store. If the store is a stack with LIFO behaviour, we obtain depth-first search; if the store is a queue
with FIFO behaviour, we obtain breadth-first search. If we have some knowledge about the nodes,
we can obtain smarter traversals by using, for example, a priority queue as the store.
store.put(root);
while (!store.empty())
{
node = store.get();
node.visit();
if (node.right != 0)
store.put(node.right);
if (node.left != 0)
store.put(node.left);
}
• empty must return true iff the store is empty and false otherwise. empty must return
false if there is any element that has been put into the store but has not been retrieved by
get.
• get must return an element from the store unless the store is empty, in which case its
behaviour is undefined.
The goal, then, is to implement a traversal function that is passed a store as argument and imple-
ments the traversal without knowing precisely how the store behaves. There are two obvious ways
in which we might implement a generic traversal function: using inheritance and using templates.
Before we show how to do this, we will look at the various features the program needs. All of the
classes are intended to have just enough complexity to support this particular application. To avoid
confusion, they use simple, pointer-based techniques rather than STL features.
First, we introduce the binary trees that are to be traversed: see Figure 56 on page 101. There is no
class for complete trees, just a class for nodes of trees. Each node has an integer key and pointers
to its left and right subtrees. Either or both of these pointers, of course, may be null.
6 TEMPLATE PROGRAMMING 100
There are two functions associated for binary trees. One of them overloads operator« and is
used as a check to see what is in the tree. The other, makeTree, constructs a tree containing all
of the keys in a given semi-closed range.
For both kinds of store (stack and queue), we will use a single-linked list to store items, as shown in
Figure 57. The main difference is that a stack accesses only one end of the list (the “top” of the stack)
and the queue accesses both ends (the “front” and “back” of the queue). We have assumed that list
items are pointers to tree nodes but, of course, we could generalize this by making ListNode a
template class.
Stores are implemented with an abstract base class with pure virtual functions for the required
operations: see Figure 58.
Figure 59 on page 103 shows the declaration of class Stack. To save space, the member func-
tions are defined in the body of the class declaration. (This is allowed, and has the side-effect of
permitting the compiler to inline them.)
Pushing an element onto the stack (put()) is easy: we just have to create a new list node and
update the pointer to the head of the list, which represents the top of the stack.
Retrieving an element from the stack is slightly harder and care is necessary. We have to get the
pointer from the first list node, delete the list node, and update the top pointer. This requires
creating temporaries, result and tmp, to store the node to be returned and the new top pointer
while we delete the old one. The assertion will detect an attempt to pop an element from an empty
stack, although this should never happen: in the traversal pseudocode of Figure 55 on page 99, we
call get only after checking that the store is not empty.
Figure 60 on page 104 shows the declaration of class Queue. The code is somewhat more compli-
cated than the stack code because we have to maintain two pointers, to the front and back of the
list.
• The list pointers run from the front of the queue to the back of the queue.
• New items are inserted at the back of the list. The back pointer is updated to point to the
new item.
• Items are removed from the front of the list. The front pointer is updated to point to the
next item in the list.
• If the list is empty, front = back = 0. When an item is inserted into an empty queue, both
front and back pointers are set pointing to it.
• If removing an item makes the front pointer null, then the back pointer must be set to
null as well, and the queue is then empty.
• The test empty examines the back pointer, although it could in fact examine either pointer.
• An undocumented class invariant: either the front and back pointers are both null, or both are
non-null.
6 TEMPLATE PROGRAMMING 101
TreeNode::~TreeNode()
{
delete left;
delete right;
}
class ListNode
{
public:
ListNode(TreeNode *ptn, ListNode *next)
: ptn(ptn), next(next)
{}
TreeNode *ptn;
ListNode *next;
};
class Store
{
public:
virtual void put(TreeNode *ptn) = 0;
virtual TreeNode *get() = 0;
virtual bool empty() = 0;
};
At this point, we have all of the code required for the demonstration. Figure 61 on page 105 shows
a generic traversal function that is passed a pointer to the abstract base class Store. This function
can be invoked either by calling
or by calling
The decision as to which kind of store to use is made at run-time. Each call to put, get, or empty
is dynamically bound to the corresponding function in either Stack or Queue. The overhead of
dynamic binding is small but could be significant if these operations are performed very often.
Figure 62 on page 105 shows a traversal function that obtains its genericity with a template. The
template parameter StoreType must be replaced by a class that provides the operations put,
get, and empty. It must also provide a default constructor that creates an empty store. This
constructor is invoked by the statement
The inheritance version does not need this statement because it is passed an empty store. Except
for this statement, the bodies of the two functions are identical.
TreeNode *get()
{
assert(top);
TreeNode *result = top->ptn;
ListNode *tmp = top->next;
delete top;
top = tmp;
return result;
}
bool empty()
{
return top == 0;
}
private:
ListNode *top;
};
traverseUsingTemplates<Stack>(tree);
or by calling
traverseUsingTemplates<Queue>(tree);
Note that we must provide the template argument <Stack> or <Queue> explicitly in calls to
traverseUsingTemplates, because the compiler cannot infer which kind of store we want
from the function argument tree. The call
traverseUsingTemplates(tree);
TreeNode *get()
{
assert(front);
TreeNode *result = front->ptn;
ListNode *tmp = front->next;
delete front;
front = tmp;
if (front == 0)
back = 0;
return result;
}
bool empty()
{
return back == 0;
}
private:
ListNode *front;
ListNode *back;
};
template<typename StoreType>
void traverseUsingTemplates(TreeNode *root)
{
StoreType *pst = new StoreType;
pst->put(root);
while (!pst->empty())
{
TreeNode *ptn = pst->get();
assert(ptn);
cout << ptn->getKey() << ’ ’;
if (ptn->getRight() != 0)
pst->put(ptn->getRight());
if (ptn->getLeft() != 0)
pst->put(ptn->getLeft());
}
}
Figure 63 on page 106 shows a program that tests the generic traversal, using both the inheritance
and the template versions, and the output from this program.
• For inheritance to work, the classes Stack and Queue must be derived from the same base
class. The traversal function has a parameter of type pointer-to-base-class.
The template solution does not require any relationship between classes Stack and Queue.
The only requirement is that each class has a default constructor that creates an empty store
and implements the required member functions.
6 TEMPLATE PROGRAMMING 106
int main()
{
TreeNode *tree = makeTree(0, 10);
cout << "Initial tree (in order): " << tree << endl;
cout << endl << "Traverse using inheritance with Stack: ";
traverseUsingInheritance(tree, new Stack);
cout << endl << "Traverse using inheritance with Queue: ";
traverseUsingInheritance(tree, new Queue);
cout << endl;
cout << endl << "Traverse using templates with Stack: ";
traverseUsingTemplates<Stack>(tree);
cout << endl << "Traverse using templates with Queue: ";
traverseUsingTemplates<Queue>(tree);
cout << endl;
delete tree;
return 0;
}
Output:
Figure 63: Test program and output for generic tree traversal
• The solutions are a trade-off between compile-time overhead and run-time overhead. Dy-
namic binding has a small performance penalty because virtual functions are called indirectly
(through a pointer) rather than directly.
Templates have no run-time overhead but it does slow down compilation, sometimes signif-
icantly. A small amount of time is spent expanding templates. Much more time is wasted
reading additional header files, because the bodies of template functions must be put in
header files rather than implementation files.
This is a real problem in practice because it considerably increases the time needed
by the compiler to compile significant programs. . . . However, real-world programs
quickly end up taking hours to compile and link (we have been involved in situa-
tions in which it literally took days to build a program completely from its source
6 TEMPLATE PROGRAMMING 107
• As a general rule, early binding provides efficiency and late binding provides flexibility. With
both versions, we can use both types of store, as the test program generates. However, we
may have to make a dynamic choice of store, as shown in the following code:
Store *ps;
if ( hconditioni )
ps = new Stack;
else
ps = new Queue;
traverseUsingInheritance(tree, ps);
If this kind of code cannot be avoided (i.e., the value of hconditioni must be evaluated at
run-time), there is no reasonable alternative to inheritance. The alternative
if ( hconditioni )
traverseUsingTemplates<Stack>(tree);
else
traverseUsingTemplates<Queue>(tree);
is not particularly attractive. It forces the compiler to generate two expansions of the traversal
function, which will occupy lots of memory, and the gain in performance will probably be
insignificant.
• In this example, the base class Store contains no code. In a larger, more practical, applica-
tion, code duplicated in derived classes could be moved into the base class.
Common code cannot be as easily shared in the template version. However, it is possible to
use the template approach with a class hierarchy and thereby to obtain the benefits of code
sharing. The difference, as before, is just that the inheritance version chooses the derived
class at run-time but the template version makes the choice at compile-time.
• In terms of maintenance, there is not a lot to choose between the two solutions. An advantage
of the inheritance version is that a new derived class can be added to the hierarchy and linked
in to the program without recompiling the traversal function. This might be useful in a large-
scale project.
Figure 64 on page 108 shows the organization of the various components of the traversal pro-
gram, not including the main function. The header and implementation files for TreeNode are
conventional. The header file store.h contains the forward declaration
6 TEMPLATE PROGRAMMING 108
class ListNode;
It does not need to contain the complete declaration of class ListNode because all of the ref-
erences to ListNode are pointers (or references). Provided that the compiler is informed that
ListNode is a class, it does not need to know how big an instance is.
The implementation file store.cpp contains the full declaration of ListNode. Since it is in an
implementation file, this declaration is inaccessible to other parts of the program. That its members
are all public does not matter, because they are only available to the class Stack and Queue.
There is no implementation for class Store because it is an abstract class that contains only pure
virtual functions.
store.h
binarytree.h #include "binarytree.h"
Declarations of class TreeNode, Forward declaration for class
free function makeTree, ListNode;
operator<< for TreeNodes. declarations for classes Store, Stack,
and Queue.
binarytree.cpp store.cpp
traversal.cpp
#include "binarytree.h"
#include "store.h"
Implementations of traverseUsingInheritance,
traverseUsingTemplates, and main.
7 Designing classes
Class design is a big topic in C++, with many aspects to consider. Since any one class does not
illustrate all of the aspects of class design, we use two example classes to illustrate the issues. The
first example class is Rational, which implements fractions and provides examples of the issues
that arise in developing a numerical or algebraic class. The second example class is Account,
which – with a bit of artifical manipulation — provides examples of memory management and
other problems.
Rational Figure 65 on page 110 shows the declaration of class Rational. Comments that would
normally be included in such a declaration have been omitted to save space. The accompanying
text provides adequate explanation.
An instance of Rational is a rational number, or “fraction”, represented by two long integers. The
n
fraction is represented by the pair (n, d). The class provides arithmetic operations (+, -, *, /),
d
and ^ (exponentiation)), the associated assignment operators (+=, -=, *=, /=), and comparisons
(==, !=, <, >, <=, >=) for fractions. It also provides stream operators for reading and writing
fractions.
Rational numbers are stored in normalized form. In the pair (n, d), we require d > 0 and gcd(n, d) =
1. (We can consider d > 0 ∧ gcd(n, d) = 1 to be a class invariant.) For example, the construction
Rational(4,-6) yields the pair (−2, 3). An attempt to create a fraction with zero denominator
raises an exception.
Account The other example class, Account, is rather different. Some of the differences are due
to the application and some are due to an intentional complication: Account has a data member
that is a pointer.
An account is associated with a person who has a name. In class Account, the name is represented
as a char* (pointer to array of characters). This introduces various problems, all of which could
be avoided by using the standard class string instead of char*. We use char*, however, just
to show what the problems are and how they can be solved.
Other differences between Rational and Account concern comparison, accessors, and muta-
tors.
Figure 66 on page 111 shows the declaration of class Account. The data members of an account
are: the name of the owner or client; an id number; and the balance in the account.
C++ does not have a type that is really suitable for financial work. Accountants do not like double
because rounding prevents precise balancing of accounts. Long integers (type long) used to repre-
sent cents are quite good, provided that input and output functions make appropriate conversions
between dollars and cents. However, the largest amount that can be represented with a long integer
is $42,949,673 — not even enough for a bank president’s annual income. To do good banking, we
would need a special currency class. Curiously, the Boost library developers have never accepted
a currency class, although examples exist17 that could be raised to the standard of a Boost class
fairly easily.
17
See, for example, http://www.colosseumbuilders.com/sourcecode.htm.
7 DESIGNING CLASSES 110
#ifndef RATIONAL_H
#define RATIONAL_H
#include <ostream>
class Rational
{
public:
Rational(long num = 0, long den = 1);
Rational & operator+= (const Rational & right);
Rational & operator-= (const Rational & right);
Rational & operator*= (const Rational & right);
Rational & operator/= (const Rational & right);
Rational operator-() const;
Rational operator^ (int e) const;
friend bool operator== (const Rational & left,
const Rational & right);
friend bool operator!= (const Rational & left,
const Rational & right);
friend bool operator< (const Rational & left,
const Rational & right);
friend bool operator> (const Rational & left,
const Rational & right);
friend bool operator<= (const Rational & left,
const Rational & right);
friend bool operator>= (const Rational & left,
const Rational & right);
friend std::istream & operator>> (std::istream & is,
Rational & r);
friend std::ostream & operator<< (std::ostream & os,
const Rational & r);
double toDouble() const;
enum Exceptions { BAD_INPUT, ZERO_DENOMINATOR };
private:
void normalize();
long num;
long den;
};
Rational operator+ (const Rational & left, const Rational & right);
Rational operator- (const Rational & left, const Rational & right);
Rational operator* (const Rational & left, const Rational & right);
Rational operator/ (const Rational & left, const Rational & right);
#endif
Figure 65: Declaration for class Rational
7 DESIGNING CLASSES 111
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
class Account
{
public:
Account();
Account(char *name, long id, long balance = 0);
Account(const Account & other);
~Account();
Account & operator=(const Account & other);
long getBalance() const;
void deposit(long amount);
void withdraw(long amount);
void transfer(Account & other, long amount);
friend bool operator==(const Account & left,
const Account & right);
friend bool operator!=(const Account & left,
const Account & right);
private:
void storeName(char *s);
char *name;
long id;
long balance;
};
#endif
Figure 66: Declaration for class Account
There are other ways, too, in which the account class given here is unrealistic and nothing like a
class that would be used in a banking application, for example. Nevertheless, the example provides
some useful insights into class design.
7.1 Constructors
All classes have constructors. If you do not provide a constructor, the compiler generates a default
constructor that allocates memory for the object but doesn’t do anything else. Except in rare
cases, for very simple classes, it is best to provide one or more constructors. If you provide any
constructor at all, the compiler does not generate a default constructor.
A default constructor is a constructor without any parameters. There are a number of situations in
which a default constructor is required; for example, an array declaration is allowed only for types
7 DESIGNING CLASSES 112
Warning There is a small but important inconsistency in C++ notation. Suppose that C is a class
with two constructors, one of which is a default constructor and consider these statements:
C c1(45);
C c2();
Unfortunately, this interpretation is wrong! In fact, c2 has been declared (but not defined) as a
function that takes no arguments and returns a C. To invoke the default constructor, you must
leave out the parentheses:
C c1(45);
C c2;
Rational Class Rational requires only one constructor. It is a general purpose constructor with
two long parameters, corresponding to the numerator and denominator of the fraction, stored
as num and den, respectively. Both parameters have default values (num = 0, den = 1), which
implies that this constructor counts as a default constructor. The constructor calls normalize
(see Figure 67 on page 113) to put the fraction in normal form.
The data members are set using initializers rather than assignments. This is the best way to initial-
ize data members and you should use it whenever possible.
void Rational::normalize()
{
if (den == 0)
throw Rational::ZERO_DENOMINATOR;
if (num == 0)
{
den = 1;
return;
}
if (den < 0)
{
num = -num;
den = -den;
}
assert(num != 0 && den > 0);
long g = gcd(abs(num), den);
num /= g;
den /= g;
}
The private member function normalize is called whenever a new fraction is created, either by a
constructor or by some other means. If den = 0, it throws the exception ZERO_DENOMINATOR,
which is one of the values of the enumeration Exceptions declared in the class. If num = 0, it
sets den = 1, to ensure that the fraction zero has the unique representation (0, 1). If den < 0,
it changes the sign of both numerator and denominator. Finally, it divides both by their greatest
common divisor to cancel common factors.
An important consequence of providing a default value for den in the constructor is that Rational(n)
constructs the pair (n, 1) corresponding to the fraction n/1. This form of the constructor is used
in a context where the compiler expects a Rational but finds a value of integral type. It allows
7 DESIGNING CLASSES 114
Account The normal constructor for an Account is passed the name, identification code, and
opening balance for the new account. If the opening balance is omitted, it defaults to zero.
The name is passed as a char*. Simply copying the pointer would be a serious mistake. As one of
the many ways in which things could go wrong, consider this function:
Account * createAccount()
{
char buffer[10000];
cout << "Please enter your name: ";
cin >> buffer;
int id;
cout << "Please enter your account ID: ";
cin >> id;
return new Account(buffer, id);
}
Since the bad guys use buffer overflow as the basis of many attacks, it is always a mistake to read
characters into a character array. To make it hard for them, we can use a long buffer. The real
problem with this function, however, is that the buffer is destroyed when the function returns. If
the new account is not to be left with a pointer into outer space, it had better make a copy of the
buffer.
This constructor does indeed make a copy of the name passed to it:
It turns out that storing the name is something that we will have to do several times. Consequently,
it makes sense to put it into a function. Space for the name is allocated dynamically (i.e., using
new, with space taken from the heap) and we must remember to allocate one character position for
the terminator, ’\0’. (We are using the old-style functions strlen and strcpy. As mentioned
above, these problems do not arise with the more modern class string.)
The normal constructor is not a default constructor because the parameters do not have default
values. We could give them default values or we could define another constructor for use as the
default, like this:
Account::Account()
: id(0), balance(0)
{
storeName("");
}
The copy constructor is an important component of every C++ class. It is used whenever an object
has to be copied. Common uses of the copy constructor include:
If we do not define a copy constructor, the compiler generates one for us. This default copy con-
structor simply copies the values of the data members of the object. The default copy constructor
for Rational does exactly what we want and there was no need to define our own version. Class
Account is different.
Class Account has the data member name, which is a pointer. The default copy constructor just
copies the pointer, not the object it points to. This would be a disaster for accounts, because we
would end up with more than one pointer pointing to the same name. If one account is deleted, the
others would be left with dangling pointers. (Technically, the copy constructor performs a shallow
copy but what we need is a deep copy.)
The copy constructor must therefore behave like the constructor, making a new copy of the name.
Fortunately, we have a function storeName that does exactly the right thing.
The signature (or prototype) of the copy constructor for a general class T is T::T(const T &).
For our class, Account, the implementation looks like this:
Define a copy constructor for any class that has pointer members.
• Declare the copy constructor T(const T &) in the private part of the class declaration.
The effect is to prevent copying of the object. By declaring the copy constructor, we prevent the
compiler from generating it. By making the copy constructor private, we prevent outsiders from
calling it. By not defining the copy constructor, we prevent member functions from using it. The
result is that any initialized declaration, passing by value, or returning by value, will be flagged as
an error by the compiler.
It is quite possible that a real-life banking application might choose to prevent copying of accounts.
This is the mechanism that could be used.
Note that preventing copying does not make Account a Singleton; we can have as many accounts
as we need, but we cannot make copies of them.
7.2 Destructor
Rational Class Rational does not have any pointer members and is not intended to be used as
a base class. Consequently, we do not define a destructor for it.
Account We must define a destructor for class Account because it has a pointer member. Later,
we will discuss using Account as a base class, which provides another reason for having a de-
structor.
The destructor must destroy any data that was created dynamically (using new) by the constructor.
Destruction is performed by delete, which has two forms:
The distinction between the two kinds of destruction is very important, because the compiler can-
not correct you if you are wrong. In Account, we must use delete [] name; if we wrote
delete name instead, only the first character of the name would be deallocated.
7 DESIGNING CLASSES 117
Account::~Account()
{
delete [] name;
}
7.3 Operators
C++ allows most operators to be overloaded. This is an extremely useful feature of the language,
but it should not be abused. If operators are defined, they should be defined consistently and they
should behave in a reasonable way.
Rational Class Rational is an obvious candidate for overloaded operators, because fractions
are numbers and users will expect to use arithmetic operations with fractions. To respect C++
conventions, if you provide +, you should also provide +=, and similarly for the other operators. It
turns out to be easier, and more efficient, to define the assignment operators (+=, -=, *=, /=) as
member functions and then to use them in the definitions of the simple operators (+, -, *, /).
Figure 68 on page 118 shows the implementation of the assignment operators. Each one normalizes
its result and returns a reference to the new fraction. This is another convention that you should
follow; it allows users to write statements such as
p += q *= r;
assuming that they can figure out what such expressions mean.
By default, the compiler will generate a default assignment operator (operator=). The effect of
this operator will be to copy all of the fields of the object. If this is what you want, you do not need
to define your own version of operator=.
Rational The default assignment operator is just what we need for Rational objects: the state-
ment r = s will copy the numerator and denominator of s to r. Consequently, we do not define
operator=.
7 DESIGNING CLASSES 118
Account Since Account has a pointer member, we must define an assignment operator for it.
Not doing so will lead to the same problems as not having a copy constructor: we will end up
with many accounts all pointing to the same name. The assignment operator looks rather like the
copy constructor, but there are two important differences. Consider the incorrect version of the
assignment operator shown in Figure 69.
Note first that the type of the assignment operator is Account& and that the function returns
*this. This is conventional for assignment operators and it allows statements such as
a1 = a2 = a3 = a4 = a5;
a = a;
and think about the effect in Account::operator= as defined above. storeName allocates
space for the name, and copies the name into. The old name lost — a memory leak. If we insert
the statement delete [] name to avoid the memory leak, things get even worse: storeName
would attempt to copy the deleted name! The solution is to check for self-assignment. These
considerations lead to the correct assignment operator shown in Figure 70.
We might ask: “What programmer could be so stupid as to write a = a?” The answer is that a
programmer might not write this assignment as such, but it could easily be generated by template
expansion. Also, a programmer might quite reasonably write
a[i] = a[j];
Define an assignment operator for any class that has pointer members. The assign-
ment operator should check for self-assignment and return a reference to *this.
7.3.2 Arithmetic
If it makes sense to perform arithmetic operations on instances of the class, we can provide the
appropriate operators. These are usually implemented in conjunction with the corresponding as-
signment operators, described above.
In general, you should implement the arithmetic functions so that they obey standard laws of
algebra. For example, - is the inverse of +, / is the inverse of *, and so on.
There are occasional exceptions to this rule. For example, string uses + for concatenation, even
though concatenation is neither commutative nor associative, and has no inverse. But people seem
to accept + as a concatenation operator, so this is perhaps excusable.
Arithmetic operators, such as operator+, can be implemented as member functions with one
parameter or as free functions with two parameters. If we implement them as member functions,
then
x + y
is effectively translated as
x.operator+(y)
The compiler will use the static type of x to choose the appropriate overload of operator+ and
may convert y to match the type of x. Suppose that we implemented + for class Rational in
this way and that i is an int and r is a Rational. Then r+i converts i to Rational and
adds the resulting fractions but i+r does not compile because the integer version of operator+
cannot accept a Rational right argument. In other words, the advantage of defining comparison
operators as free functions is that the order of operands does not matter.
There is another issue to consider when we choose to implement free functions associated with
a class: do we provide access functions for data members of the class, or do we declare the free
functions as friends? The choice depends very much on the particular application. For example,
if the class already provides accessor functions for some reason, the free functions can make use of
them. If security is important, and data members should not be exposed, then friend functions
may be a better choice.
Rational Figure 71 on page 121 shows the standard arithmetic operators for class Rational,
implemented as free functions that use the corresponding assignment operators. Since class
Rational does not export the numerator and denominator of a fraction, they are declared as
friends of the class.
If you give users the arithmetic operators, they will expect unary minus as well. Unary minus is best
implemented as a member function with no arguments. It does not negate the value of the fraction,
but instead returns the negated value while remaining unchanged. Consequently, we can qualify it
with const.
Rational operator+ (const Rational & left, const Rational & right)
{
Rational result = left;
result += right;
return result;
}
Rational operator- (const Rational & left, const Rational & right)
{
Rational result = left;
result -= right;
return result;
}
Rational operator* (const Rational & left, const Rational & right)
{
Rational result = left;
result *= right;
return result;
}
Rational operator/ (const Rational & left, const Rational & right)
{
Rational result = left;
result /= right;
return result;
}
Figure 71: Arithmetic operators for class Rational, implemented using the arithmetic assign-
ments of Figure 68 on page 118
C++ programmers expect to use pow for exponentiation. But pow takes arguments of many types,
even for the exponent. For fractions, we take the slightly daring approach of providing ^ as an
exponential operator. The exponent must be an integer, but the integer may be positive or negative:
−e e
n d
is evaluated as . If r = 0, then r e will fail (throwing an exception) if e < 0. The function
d n
e
uses the identity x2e = x2 when e is even to achieve complexity O(log e) rather than O(e). Since
exponentiation is not commutative, and the left operand must be a Rational, we implement
operator^ as a member function, as shown in Figure 72 on page 122.
There is a minor problem with using operator^ as an exponent operator. Although we can
overload operators in C++, we cannot change their precedence. As it happens, operator^, which
is normally used as exclusive-or on bit strings, has a lower precedence than the other arithmetic
operators. Its precedence is even lower than that of operator<< and operator>>. So we had
better warn our users to put exponential expressions in parentheses!
7 DESIGNING CLASSES 122
7.3.3 Comparison
There are two important kinds of comparison: equality and ordering. Identity comparison corre-
sponds to the operators == and != and is useful for many kinds of objects. Ordering corresponds
to the operator < and its friends and is useful only for objects for which some kind of ordering
makes sense.
By convention, the ordering operators return a Boolean value true or false. They can implement
only a total ordering in which, for any objects x and y, one of the following must be true: x < y,
x = y, or x > y. They cannot be used to implement a partial ordering, in which two objects may be
unrelated.
Figure 73 on page 123 shows the corresponding functions for class Rational. Like the arithmetic
operators, they are implemented as free, friend functions.
Account Considering the comparison operators for class Account raises interesting questions
about equality.
• If it does make sense, what does it mean to say “account A equals account B”?
Comparing balances probably is not very helpful. Comparing names is unsafe, because two people
might have the same name.18 There are two comparisons that might be reasonable:
• Two accounts are equal if they have the same ID (extensional equality)
• Two accounts are equal if they are the same object (intensional equality or identity)
18
This is, in fact, the cause of many “mistaken identity” problems.
7 DESIGNING CLASSES 123
bool operator== (const Rational & left, const Rational & right)
{
return left.num * right.den == right.num * left.den;
}
bool operator!= (const Rational & left, const Rational & right)
{
return !(left == right);
}
bool operator< (const Rational & left, const Rational & right)
{
return left.num * right.den < right.num * left.den;
}
bool operator> (const Rational & left, const Rational & right)
{
return left.num * right.den > right.num * left.den;
}
bool operator<= (const Rational & left, const Rational & right)
{
return left < right || left == right;
}
bool operator>= (const Rational & left, const Rational & right)
{
return left > right || left == right;
}
The following comparison functions check for identity (accounts are equal only if they are the same
object). Note that this is not really realistic because, in a practical application, account objects
would spend most of their lives on disks and would only occasionally be brought into memory.
Accounts could be ordered by name or by ID; this would allow us to sort a vector of accounts,
for example. These operators are easy to add if needed.
For many classes, it useful to provide the insertion operator (<<), if only for debugging purposes.
The extraction operator, >>, is less often needed, but can be provided as well. When these operators
are provided, they are commonly implemented as friends.
Rational For fractions, both input and output operators make sense, as we implement them as
friends. Both present complications.
For input, the first decision we have to make is: what should the user enter? Let’s say that the user
must enter two integers separated by a slash:
The next decision is: how does the program respond if the user does not enter the data in the
form that we expect? There are many possible solutions, ranging from accepting only input that is
exactly correct to parsing what the user enters and figuring out what was meant.
In the following function, we follow a middle way: we read an integer, a character, and another inte-
ger, and we throw an exception if the character is not ’/’. Although rationals can be constructed
from integers, the user is required to enter a complete fraction, even if it is 3/1.
Output is usually more straightforward than input, but there is one problem. Suppose that we
implement the inserter in the “obvious” way
in which r is a Rational. Our function will use 12 columns to write the numerator and then will
write the slash and the numerator — probably not what the user expected!
Of the various ways to correct this error, the simplest is to format the entire fraction, in the obvious
way, into a buffer, and then to insert the buffer into the output stream. This ensures that any width
modifiers will be applied to the complete fraction, not just to the numerator.
The remaining issue is how to write whole numbers (fractions with denominator 1). To avoid silli-
nesses like 3/1, we will not write the slash or the denominator for whole numbers. This reasoning
leads to the following function.
String streams can be used for either output (ostringstream) or input (istringstream) and
require the directive
#include <sstream>
• An output string stream behaves like any other output stream (e.g., cout).
• After writing things to it, you can extract the string of formatted data using the function str,
which returns a string.
• After str has been invoked on an ostringstream, the stream is frozen and does not
permit further write operations.
• When the string stream is deleted (usually at the end of the current scope), data associated
with it is deleted.
An input string stream can be used to parse a string. In the following code, the input string stream
isstr is initialized with myString. The isstr is used, like any other input stream (e.g., cin),
with extract operators.
7.4 Conversions
Conversions are a delicate issue in C++. Programmers don’t like writing explicit conversions and
want the compiler to do the dirty work for them but too many conversions can be a bad thing.
7 DESIGNING CLASSES 126
Rational It seems reasonable to convert rationals to floating-point numbers. Sometimes, for ex-
ample, we might want 0.66667 rather than 2/3. C++ provides a powerful way of implementing such
conversions, using operator notation. We can define a conversion from Rational to double by
adding this member function to class Rational:
This function provides an implicit conversion from Rational to double: in any context where
the compiler expects to find an expression of type double, but in fact finds an expression of type
Rational, it will insert a call to this function to perform the conversion.
Unfortunately, this solution is too effective! If we write 1/r, for example, the compiler complains
about ambiguity. In 1/r, it can either convert 1 to Rational and evaluate the reciprocal of
r as a Rational or it can convert both 1 and r to double and evaluate the reciprocal of r
as a double. Since we would like to keep the convenience of being able to write 1/r for the
Rational reciprocal of a Rational, we choose not to provide operator double.
It is not hard to find a better alternative: we simply provide the same function with a funny name
to prevent the compiler from using it implicitly. The following function does what we need and will
be invoked only when the user explictly requests it by writing r.toDouble().
7.5 Accessors
An accessor or inspector is a member function that returns information about an object without
changing the object. It follows immediately from this definition that accessors should always return
a non-void value and should be declared const.
Rational The only candidates for accessors for class Rational are getNum and getDen, im-
plemented in the obvious way. The decision not to provide these was that the representation of a
rational number is a “secret” and providing these accessors would give away part of the secret.
If the class did provide getNum and getDen, the friend functions would no longer need to be
declared as friends.
Account There are several candidates for accessors for class Account. We provide just an ac-
cessor for the account balance, to demonstrate the general idea.
7.6 Mutators
A mutator is a member function that changes the state of the object. Usually, the return type of a
mutator is void (otherwise the mutator would be a function with a side-effect).
Rational Any function that changes the state of a rational should do so in a way that makes
semantic sense. Thus += is acceptable, because it changes the state by adding another rational.
Arbitrary mutations of the numerator and denominator do not make semantic sense, and so we do
not provide mutators for class Rational.
Account There are several ways in which the state of an account may reasonably be changed. We
provide three “obvious” functions: deposit, withdraw, and transfer. Of these, deposit
is straightforward.
For withdrawals, we have to decide what to do when the balance would go negative. The solution
adopted here is to throw an exception. Since we do not know who will be handling the exception, we
must ensure that sufficient information is provided. To achieve this, we declare a special exception
class (described below) and store the account ID and a helpful message in the exception object.
Standard exception classes provide a function what that returns a description of the exception.
Although we could inherit from one of the standard exception classes, we choose not to do so here,
but we provide what anyway. Figure 74 on page 128 shows the declaration and implementation of
the class AccountException.
The third mutator for class Account is transfer, which transfers money from one account
to another. We allow an account to transfer funds to another account but not to transfer funds
from another account. This function will throw an exception if the transfer would leave the giving
account with a negative balance.
class AccountException
{
public:
AccountException(long id, std::string reason);
std::string what();
private:
long id;
std::string reason;
};
string AccountException::what()
{
ostringstream ostr;
ostr << "Account " << id << ". " << reason << ’.’;
return ostr.str();
}
The function transfer is implemented using the previously defined functions withdraw and
deposit. It is always a good idea to use existing code when it applies, rather than introducing
more code, with possible errors.
In real-life banking, an operation such as transfer must be implemented very carefully: either
the transaction must succeed completely, or it must fail completely and have no effect. (Database
gurus are familiar with this problem of transaction integrity.) Without pretending that transfer
is really a secure function, we note that there is only one (obvious) way that it can fail — withdraw
may throw an exception — and that this failure leaves both accounts unchanged.
C++ allows us to overload the “operator” []. The overload has one parameter, which can be of any
type, and returns a value, which can be of any type. The syntax for calling the function is a[i],
in which a is an object and i is the argument passed to the function. Typically, we would use
operator[] for a class that represented an array, vector, or similar kind of object. Figure 75
on page 129 shows an inefficient and incomplete map class that associates names with telephone
numbers, both represented as strings. The store is accessed by calling operator[] with a string
argument. The following code illustrates the use of this store (note the final statement).
7 DESIGNING CLASSES 129
template<typename T>
class Store
{
public:
void insert(string key, T value)
{
data.push_back(pair<string, T>(key, value));
}
T operator[](string key)
{
for ( vector<pair<string, T> >::const_iterator it =
data.begin();
it != data.end();
++it )
if (it->first == key)
return it->second;
return T();
}
private:
vector<pair<string, T> > data;
};
Store<string> myPhoneBook;
myPhoneBook.insert("Abe", "486-2849");
myPhoneBook.insert("Bo", "982-3847");
cout << myPhoneBook["Abe"];
In this example, operator[] has one parameter. This is the only possibility: you cannot declare
operator[] with no parameters or with more than one parameter.
C++ allows us to overload the “operator” (). The overload has one parameter, which can be of any
type, and returns a value, which can be of any type. The syntax is f(x), in which f is an object
and x is the argument passed to the function. Typically, we would use operator() in a situation
where it makes sense to treat an instance as a function.
The Command pattern (Gamma, Helm, Johnson, and Vlissides 1995, page 233) “encapsulates a
request as an object, thereby enabling you to parameterize clients with different requests, queue
or log requests, and support undoable operations”. At the appropriate time, a request is acti-
vated in some way. The Gang of Four use a function called Execute to activate a request, but
operator() provides a slightly neater solution.
The Command shown in Figure 76 on page 130 class stores requests to print messages. The mes-
sage to be printed is passed as an argument to the constructor. To activate a command c, the user
7 DESIGNING CLASSES 130
class Command
{
public:
Command(string message) : message(message) {}
void operator()() { cout << message << endl; }
private:
string message;
};
vector<Command> commands;
commands.push_back(Command("First message"));
commands.push_back(Command("Second message"));
// ....
for ( vector<Command>::iterator it = commands.begin();
it != commands.end();
++it )
(*it)();
writes c().
For example, commands can be stored in a vector and then activated sequentially, as shown in
Figure 77 on page 130.
You can declare operator() with any number of parameters and the syntax is conventional: see
Figure 78.
class Test
{
public:
void operator()(int i, int j) { cout << i+j << endl; }
};
int main()
{
Test t;
t(5,6);
}
A constructor with a single parameter provides a form of type conversion. For example, suppose
class Widget has a constructor with a parameter of type int:
class Widget
{
public:
Widget(int n);
....
This constructor gives the compiler permission to convert an integer to a Widget whenever it has
an opportunity to do so. This behaviour might be appropriate, but it might also be an error. For
example, class string has a constructor with an integer argument so that
string s(N);
string s = ’a’;
constructs a string with 97 characters — probably not what the programmer intended.
In fact, this does not happen, because the string constructor does not allow implicit conversions.
The conversion is prevented by qualifying the constructor with explicit. To prevent Widgets
being constructed from integers, rewrite the example above as
class Widget
{
public:
explicit Widget(int n);
....
The keyword explicit does not prevent the constructor from being used at all, of course. It says
that, in order to use this constructor, the call Widget(N) must actually appear in the program;
the compiler will never call the constructor implicitly.
The keyword explicit can be used with constructors only; it cannot be used with conversion
operators such as operator double described in Section 7.4.
7.7.4 Friends
A function associated with a class can have three properties (Stroustrup 1997, page 278):
Property 2 means that the function f associated with class C must be invoked in one of the following
ways:
• C::f()
Property 3 means that statements in the function can use the this pointer to the object for which
the function is invoked.
The following table shows which kinds of function have these properties:
Property
Function kind 1 2 3
√
friend
√ √
static
√ √ √
member
The table shows that the three kinds of function form a hierarchy, with member functions having
the most, and friend functions the least, access to the class.
Contrary to popular belief (especially amongst Java programmers), friends do not violate encapsu-
lation in C++. The important point is that friends must be declared within the class. This means that
a class has complete control over its friends — enemies cannot use friends to subvert the class’s
protection mechanisms. Here is Stroustrup’s opinion of friends:
• A function or a class can be declared as a friend. In either case, friends of a class can
access private members (data and functions) of the class.
• Two or more classes can declare the same class or function as a friend.
7 DESIGNING CLASSES 133
Used correctly, friends actually provide better protection than other techniques. Here is an example
(Stroustrup 1997, page 278): we have classes Vector and Matrix and we want to define func-
tions that, for example, multiply a matrix by a vector. We could define the multiply function as a
free function, external to both classes, but then we would have to expose the representations of
both Vector and Matrix for this function to use. Instead, we use friends:
class Vector
{
friend Vector operator* (const Matrix & m,
const Vector & v);
....
}
class Matrix
{
friend Vector operator* (const Matrix & m,
const Vector & v);
....
}
This provides a neat solution to the problem: the multiply function has access to private data in
both classes but we have not “opened them up” to anyone else.
Nevertheless, if there is a choice between a member function and a friend, it is better to use a
member function. The main reason for this preference is conversion: in the class f(x,y), the
compiler may perform conversions to match the types of the arguments x and y to the parameter
types. The call x.f(y) invokes X::f where X is the class of X (although y may still be converted).
8 INHERITANCE AND TEMPLATES 134
Some of the topics in this section are discussed more fully in Scott Meyers’s book (1992, Items 35
through 44), although you should note that this book is quite old (1992) and occasionally refers to
problems that have been solved in more recent versions of C++.
We will use (mostly) C++ terminology for inheritance: a derived class inherits from a base class.
Inheritance may be public (the most common case) or private, depending on the keyword
used before the base class in the derived class declaration:
Perhaps the most confusing aspect of the word “inheritance” is that it is used with several quite
different meanings:
We refer to the first case as interface inheritance and the second case as implementation
inheritance.19
The implementation mechanisms for these kinds of inheritance in C++ are, roughly:
19
These correspond roughly to implements and extends in Java. Note, however, that Java implements
corresponds to interface inheritance in C++ and Java extends corresponds to implementation inheritance in C++.
8 INHERITANCE AND TEMPLATES 135
1. public inheritance
2. private inheritance
The distinction between 1(a) and 1(b) can become blurred. A base class with one or more pure
virtual functions is called an abstract base class (or “ABC”) and defines, in effect, an interface: this
is 1(a). A base class with implemented virtual functions is a complete, working class that can be
specialized by derived classes that inherit some or most of its implementation and modify the rest:
this is 1(b). In between, there are base classes with a mixture of pure and impure virtual functions,
defining a sort of partially-implemented interface.
It is very important not to confuse “is-a” with “has-a”. In some (older) books, you may see things
like Figure 79 described as “inheritance hierarchies”. But this is a “has-a” hierarchy: a car has an
engine, an engine has pistons, etc. It is absurd to say “a valve is an engine” or “a handle is a door”.
Hierarchies of this kind are represented by layering (also called composition), in which an instance
of class Car contains instances of classes Door, Wheel, and Engine, etc.
car
Figure 80 shows a popular example used to demonstrate the “difficulties” of inheritance. There are
various solutions for this “problem”. One solution is to redefine Penguin::fly:
This is not a good solution, because it violates the rule that a penguin is-a bird: a penguin is
not a bird, because birds fly and penguins don’t. Figure 81 shows a better solution obtained by
realizing that the class hierarchy that we have defined is incomplete: there are birds that fly and
birds that don’t fly. The revised class hierarchy easily accommodates kiwis, ostriches, turkeys, and
cassowaries.
8 INHERITANCE AND TEMPLATES 136
class Bird
{
public:
virtual void fly();
....
};
int main()
{
Bird pb = new Penguin();
pb->fly(); // oops - penguins can’t fly!
}
class Bird
{
public:
// no definition of fly()
....
};
8.1.1 Slicing
A derived class inherits data members from its base class and may define its own data members.
Consequently, a derived class instance d is as large or larger than an instance b of the correspond-
ing base class. There are several consequences:
• The assignment b = d is allowed. Since the data in d does not fit into b, it is not copied: we
say that d is sliced. Slicing occurs not only during assignment but also when a derived object
is passed or returned by value and the destination is a base class object.
• The assignment d = b is not allowed because it would leave the derived data in d undefined.
• It is usually a mistake to use the base class of a hierarchy as a template argument. Consider:
vector<Base> bases;
Derived der( .... );
bases.push_back(der);
Since the argument of push_back is passed by value, der is sliced; data in Derived but
not in Base is lost. To avoid this problem, use pointers, as in vector<Base*>.
Slicing does not occur when we address the object through references or pointers. Suppose that
pb is a pointer to a base class object and pd is a pointer to an instance of a derived class. Then:
• The assignment pb = pd is allowed. After the assignment, pb will point to the complete
object, containing base and derived data, but only base class functions and data will be acces-
sible, because of the type of pb. Assignments of this kind are called upcasts because they go
“up” the class hierarchy, from derived class to base class..
• The assignment pd = pb is not allowed. Allowing it would give the program apparent access
to functions and data of the derived class, but those fields do not exist. Assignments of this
kind are called downcasts, because they go “down” the class hierarchy.
References work in the same way as pointers: whenever we have the address of an object (that is, a
reference or a pointer to it), slicing does not occur and dynamic binding works.
For now, the thing to remember upcast good, downcast bad. We will discuss these casts in more
detail later.
Constructors and destructors work in a special and well-defined way with derived classes.
• When a constructor of a derived class is called, the constructor of the base class is invoked
first, then the constructor of the derived class.
• When the destructor of a derived class is called, the destructor for the derived class is invoked
first, then the destructor for the base class.
8 INHERITANCE AND TEMPLATES 138
class Parent
{
public:
Parent() { cout << "Construct Parent" << endl; }
~Parent() { cout << "Destroy Parent" << endl; }
};
int main()
{
GrandChild g;
}
This behaviour is illustrated by the code in Figure 82. When this program is executed, it prints:
Construct Parent
Construct Child
Construct GrandChild
Destroy GrandChild
Destroy Child
Destroy Parent
Designing a class is difficult because you have to think about all the ways in which the class might
be used. Designing a base class is harder still, because you have to think about the people who
want to inherit from your class as well as the people who want to use it. The differences between a
simple class and a potential base class are:
• virtual functions
8 INHERITANCE AND TEMPLATES 139
• protected attributes
Virtual functions open up the possibility of redefinition in derived classes, leading to polymorphic
behaviour. Protected attributes can be accessed by derived classes but not by outsiders. These two
features combine to make inheritance useful and manageable.
• There must be a reference, rd, or a pointer, pd, to the object d. These might be defined as:
B & rd = d;
B * pd = &d;
• The function f must be invoked using either a reference or a pointer, as in these statements:
rd.f();
pd->f();
Each of these statements will call the redefined function D::f(), even though rd (pd) is a
reference (pointer) to the base type. This is polymorphism.
A virtual function may be pure virtual, meaning that it has no implementation. The body of a pure
virtual function is written using the special notation =0. A class that has one or more pure virtual
functions cannot be instantiated. It may have constructors, but these constructors can be called
only by derived classes that provide definitions for the virtual functions.
There are essentially three different kinds of member function in a base class: normal functions,
virtual functions, and pure virtual functions. The following base class has on example of each kind.
class Animal
{
public:
string getName() { .... }
virtual void move() { /* how to walk */ };
virtual void communicate() = 0; // no implementation
....
};
8 INHERITANCE AND TEMPLATES 140
From this declaration, we can infer the following intentions of the designer of the Animal class
hierarchy. Assume that pa is a pointer declared as Animal* but actually pointing to an instance
of a class derived from Animal.
• Function communicate is a pure virtual function. In this example, the use of a pure virtual
function suggests that there is no default behaviour for communication. It corresponds to the
fact that animals communicate in many different and unrelated ways (using sound, gesture,
smell, touch, etc.). Since class Animal has a pure virtual function, it cannot be instantiated:
there are no objects of type Animal. This corresponds to the real world, where if you see an
“animal”, it is always a particular kind of animal: aardvark, beaver, cat, dog, elephant, giraffe,
hedgehog, etc. Any class for which instances are needed must provide an implementation of
communicate.
There is one function that should always be virtual in a base class: it is the destructor. If a class is
intended as a base, declare:
class Base
{
public:
virtual ~Base() { .... }
....
};
8 INHERITANCE AND TEMPLATES 141
class Base
{
public:
~Base() { cout << "Deleting Base" << endl; }
private:
int x;
};
int main()
{
Base * pb = new Derived;
delete pb;
}
To see the importance of this, consider the code in Figure 83. Running this program produces the
following output:
Deleting Base
We have constructed an instance of Derived, containing data members x and y, but the run-time
system has deleted an instance of Base, with data member x only. The memory occupied by y will
almost certainly not be deallocated — a memory leak!
class Base
{
public:
virtual ~Base() { cout << "Deleting Base" << endl; }
....
Deleting Derived
Deleting Base
8 INHERITANCE AND TEMPLATES 142
class Animal
{
public:
Animal() : name("Freddie") {}
string getName() { return name; }
private:
string name;
};
Although it is possible, redefining non-virtual functions is not a good idea, for several reasons
(Meyers 1992, Item 37). Suppose that we define some variables:
Bison b;
Animal *pa = &b;
Bison *pb = &b;
These definitions give us two pointers, pa and pb, pointing to the same object, b. It is therefore
something of a surprise when we execute
and obtain
Freddie
Grrrrr
8 INHERITANCE AND TEMPLATES 143
What has happened here is that, since Animal::getName is not virtual, the compiler uses
the type of the pointer to choose the function. Thus pa causes Animal::getName to be called
and pb causes Bison::getName to be called.
If Animal::getName was a virtual function, then the function called would depend on the
type of the object, not the pointer. This is more natural behaviour: we expect a bison to answer
"Grrrrr" whether we refer to it as an animal or as a bison (at least in this example).
More formally, overriding a non-virtual function is a violation of the is-a relationship. The purpose
of a non-virtual function in a base class is to define behaviour that is invariant over the whole class
hierarchy. In the example, to be an Animal (that is, to satisfy the predicate “is-a Animal”), you
must respond to getName by returning your name. If you don’t do that, you are not an Animal
and do not belong in the Animal hierarchy. There are two possibilities:
• It is essential that bisons have a way of saying "Grrrrr". In this case, the function that
does this should not be called getName.
• It is correct modelling to say that bisons reply "Grrrrr" when asked their name. In this
case, Animal::getName should be a virtual function.
Attributes in the public part of a class declaration are accessible to anyone who owns an instance
of the object. Attributes in the private part of the declaration are accessible only to members
and friends of the object.
A class declaration may contain a third part, introduced by the keyword protected, for attributes
that are accessible to members and friends of classes derived from the class.
According to Stroustrup (1994, page 301), the keyword protected was introduced into C++ at
the request of Mark Linton, who was writing Interviews, an extensible X-windows toolkit. Five years
later, Linton banned the use of protected data members in Interviews because they had become
“a source of bugs: ‘novice users poking where they shouldn’t have in ways they ought to have
known better than’ ”. Stroustrup goes on to say (1994, page 302):
So there you have it from the master: use protected data if you have to, but prefer using
protected functions to access private data members of the base class.
8 INHERITANCE AND TEMPLATES 144
class Account
{
public:
Account();
Account(std::string name, long id, long balance = 0);
Account(const Account & other);
virtual ~Account();
Account & operator=(const Account & other);
const std::string getName() const;
long getID() const;
long getBalance() const;
virtual void deposit(long amount);
virtual void withdraw(long amount);
virtual void transfer(Account & other, long amount);
friend bool operator==(const Account & left,
const Account & right);
friend bool operator!=(const Account & left,
const Account & right);
friend std::ostream & operator<<(std::ostream & os,
const Account & acc);
protected:
void setID(long newID);
void setBalance(long newBalance);
private:
std::string name;
long id;
long balance;
};
As an example of base class design, we will take class Account from Section 7 (see page 111)
and redesign it as a base class. Class Account is quite appropriate as a base class, because banks
provide many kinds of account, and the various kinds are often represented as a hierarchy of classes
in banking software. A number of design decisions are mentioned or implied in the following notes;
few of them are cast in stone, and most might be made differently in specific circumstances.
Figure 84 shows the new version of class Account. The type of Account::name has been
changed from char* to std::string, to avoid the memory management problems that we
encountered in Section 7. Some of the functions, and the class AccountException, are not
changed, and we do not repeat their descriptions here. The redesign takes into account the follow-
ing considerations.
8 INHERITANCE AND TEMPLATES 145
• We provide some accessors (getName, getID, and getBalance) that were not present
in the original class but are likely to be useful. They are public and non-virtual, since
they access private data members and there should never be a need to redefine them. As
explained above, these functions express invariant properties of the account class hierarchy:
the meaning of getBalance is independent of the type of account we are dealing with.
Figure 85 shows their definitions.
• The definitions of deposit, withdraw, and transfer are not changed. However, it is
quite possible that a derived class might need to modify their behaviour; consequently, we
declare them to be virtual.
• There are some functions that should be available to derived classes but not to everybody.
These functions are declared in the protected section of the class declaration. This group
consists of the new functions setID and setBalance, which have obvious definitions:
Designing a derived class is usually easier than designing a base class because there are fewer
options. The base class designer has decided what gets inherited and what can be redefined; the
derived class designer has to decide:
If there are no new data or functions, there is probably no need for a derived class at all. In a
banking application, for example, it would be pointless to introduce new classes for different rates
of interest: the interest rate is just a data member of an appropriate base class.
Some functions cannot be inherited and must be defined if the derived class needs them. The
functions that are not inherited are:
• constructors
• friends
Derived class constructors can, and usually should, call the base class constructors explicitly, as in
this example:
class Base
{
public:
Base(int n) { .... }
};
The Liskov Substitution Principle provides a helpful guideline for designing derived classes:
In this section, we develop a class SavingsAccount derived from the base class Account.20
The important features of a savings account are:
• SavingsAccount has a default constructor and a full constructor that allows all data for
the account to be initialized.
• A savings account collects interest. SavingsAccount has a data member for the interest
rate and a member function for computing interest and adding the interest to the balance.
• Interest is paid only if the balance exceeds a specified minimum. SavingsAccount up-
dates the minimum balance when money is withdrawn from the account.
• The insertion operator<< shows the interest rate and minimum balance for the SavingsAccount
in addition to the information shown for a Account.
Figure 86 shows the class declaration for savings accounts. The class declaration contains exactly
those functions that we wish to define or redefine.
• minimumBalance is the minimum balance that the client must maintain over each period
in order to earn interest.
Since constructors are not inherited, we must define constructors for SavingsAccount. These
constructors can, and should, invoke the base class constructors when necessary. The default
constructor uses the default constructor of class Account and sets the new data members to
zero.
SavingsAccount::SavingsAccount()
: Account(), rate(0), minimumBalance(0), lowestInPeriod(0)
{ }
The full constructor allows the caller to specify all of the fields of an account with default values
for the balance, rate, and minimumBalance. Like the default constructor, it calls the base
class constructor and initializes the new data members separately.
The copy constructor must call the copy constructor for the base class and then initialize the new
data members explicitly. Calling the copy constructor for Account with the SavingsAccount
other is an example of upcasting.
The assignment operator is implemented by using *this (implicitly) to call the assignment oper-
ator of the base class, and then assigning the new data members explicitly.
We must update the value of lowestInPeriod whenever the balance might get smaller. This
can happen only when money is withdrawn from the account. We override the definition of
Account::withdraw with a function that updates lowestInPeriod.
The new function addInterest, which we assume is called periodically, checks that the client
has the required minimum balance and, if so, adds interest. Since balance is private, addInterest
must call the protected member function Account::setBalance to update the balance. This
function also reinitializes lowestInPeriod.
void SavingsAccount::addInterest()
{
if (lowestInPeriod >= minimumBalance)
{
long interest = static_cast<long>(rate * getBalance());
setBalance(getBalance() + interest);
}
lowestInPeriod = getBalance();
}
If sa1 and sa2 are savings account objects, the expressions sa1 == sa2 and sa1 != sa2
compile and evaluate correctly. This is not because operator== and operator!= are inherited
from Account but because the compiler can convert sa1 and sa2 to Account.
Figure 87 shows a short test program for accounts and savings accounts. When it is run, this
program displays:
8 INHERITANCE AND TEMPLATES 150
The first two lines show that an account can be constructed and copied. The next two lines show
that Charles earns $15 interest because his balance is greater than $1,000. After transferring $1,000
to Anne, his balance drops to $500 and does not earn interest, as shown in the last two lines.
Note that the transfer is performed using a reference to an Account, not a SavingsAccount.
(This is realistic, because the object doing the transferring should not have to know the kind of
accounts involved in the transfer.) Since transfer is not redefined in SavingsAccount, the
function called is Account::transfer. When transfer called withdraw, it uses this,
which is a pointer to a SavingsAccount object. Consequently, SavingsAccount::withdraw
gets called, and updates the lowest balance.
After completing the base class Account and the derived class SavingsAccount, we notice
that there is information that might be helpful to users: does a particular account pay interest? It
is easy to add a function to SavingsAccount:
This is of little use, however, to the owner of a pointer to an Account that may or may not be
a SavingsAccount. If paysInterest is to be useful, it must be declared virtual in the
base class, Account:
Thus, by default, an account class does not pay interest. Any class corresponding to an account
that does pay interest must redefine paysInterest to return true.
This seems fairly innocuous: after all, the question ‘does it pay interest?’ can be asked of any
account, and therefore the function paysInterest should be defined in the base class. The
problem — trivial in this example — is that the concept of ‘paying interest’ is not otherwise men-
tioned in class Account.
In a hierarchy with many classes, there will be many functions of this kind. The base class will
become cluttered with accessors that provide specialized information that is only relevant to par-
ticular derived classes. This can become a maintenance problem because, each time one of these
functions is added, the base class is changed, requiring recompilation of the entire hierarchy. Un-
fortunately, there does not seem to be a clean solution to this problem.
In this section, we discuss the development of a template class with features similar to an STL
container. Koenig and Moo (2000, Chapter 11) provides a very similar presentation.
Our objective is a class Vec that behaves in more or less the same way as the STL class vector.
We will provide memory management, but in a somewhat less sophisticated way than Koenig and
Moo (2000). We will obtain the class declaration by filling in the blanks of this skeleton:
The data in the vector will be stored in a dynamic array of the template type, T. We need a pointer
to the first element of the array and either: (a) the number of elements in the array, or (b) a pointer
to one-past-the-last element of the array. Following STL conventions, we will adopt choice (b) and,
of course, the user will see our pointers as iterators.
It would be possible to store exactly the number of elements that we need. This can be inefficient,
however, if the user inserts elements into the array one at a time. Consequently, we provide a
pointer to one-past-the-last element that is actually in use and another pointer to one-past-the-last
element that is available for use. The three pointers are
8 INHERITANCE AND TEMPLATES 152
• The range [avail, limit) contains the allocated but uninitialized space
Figure 88 shows these pointers for an array in which 8 elements are in use and 13 elements are
available altogether.
1 2 3 4 5 6 7 8
Following STL conventions, class Vec defines several types for its clients. These types hide, for
example, the fact that Vec uses pointers to implement iterators. (We do not hide this fact because
we are ashamed of using pointers, but rather to present a consistent abstraction to our clients.) The
types we define are:
We will provide three constructors: a default constructor; a constructor that specifies a (number of
elements) size and an initial value for each element; and a copy constructor. The default constructor
creates an empty vector. We declare the second constructor to be explicit to avoid accidental
conversion. In the second constructor, the value of the element defaults to T(), which implies
that the type T provided by the user must have a default constructor. Clearly, we will also need a
destructor. Figure 89 shows the class declaration with the features we have incorporated so far.
8 INHERITANCE AND TEMPLATES 153
Vec();
explicit Vec(size_t n, const T & val = T());
Vec(const Vec & other);
~Vec();
// rest of interface
private:
iterator data;
iterator avail;
iterator limit;
};
Figure 90 shows implementations for the constructors and destructor. Because this is a template
class, these declarations are in the header file vec.h after the class declaration. The second con-
structor is inefficient: for example, if the caller assumes the default value for the second parameter,
the constructor T() will be called 2n times: n times for new T[n] and another n times in the for
statement. Koenig and Moo (2000) show how to avoid this inefficiency by allocating uninitialized
memory, but we will not bother with this improvement.
The copy constructor requires a function that returns the size (number of elements) of the Vec
object:
Since the assignment operator is somewhat similar to the copy constructor, we consider it next.
Although they are similar, the difference between assignment and initialization is significant and
must not be overlooked. Before assigning to a variable, we must destroy its current value. Also, as
we have seen previously, we must provide the correct behaviour for the self-assignment, x = x.
The implementation of operator= shown in Figure 91 takes care of all this. The constructors
and assignment operator introduce duplicated code into the implementation, but we can clean that
up later.
It is straightforward to define the functions begin and end that provide clients with iterators
pointing to the first and one-past-the-last elements. Two versions are required, one returning an
iterator and the other returning a const_iterator.
8 INHERITANCE AND TEMPLATES 154
These functions provide all that is needed for code such as this loop
because the operators !=, ++, and * are all provided for pointers.
We enable the user to subscript Vecs by implementing operator[]. Two overloads of this
operator are required:
The need for two versions arises as follows. We want a version of operator[] that allows us
to use subscripted elements on the left of an assignment, as in a[i] = e. The first version of
operator[] does this by returning a reference. But the compiler will not accept this function if
it is applied to a const Vec, because the reference makes it possible to change the value of the
object. Consequently, we need a second version that returns a const T & and promises not to
change the object. Consider the following code:
Vec<int> v(5);
v[3] = 5; // (1)
The statement labelled (1) fails if the first (non-const) version of operator[] is omitted, be-
cause it changes the value of v. The statement labelled (2) fails if the second (const) version
of operator[] is omitted, because the compiler needs assurance that the call w[2] does not
change the value of w.
Normally, we cannot provide two versions of a function with the same parameter list. In this case,
the object (*this) is an implicit first parameter, and the overloads distinguish a const Vec and
a non-const Vec.
As with similar STL functions, neither version of operator[] checks to see if the subscript is in
range. Such a check could easily be added, perhaps as an assertion.
The next function that we provide is push_back, which appends a new value to the end of the
array. There are two cases: if there is space already allocated, we store the new element at the
position indicated by avail and then increment avail. In the other case, avail = limit,
and we must allocate more space. We will introduce a private function, grow, to find more space.
Figure 92 shows the definitions of both functions.
8 INHERITANCE AND TEMPLATES 156
template<typename T>
void Vec<T>::push_back(const T & val)
{
if (avail == limit)
grow();
*avail = val;
++avail;
}
template<typename T>
void Vec<T>::grow()
{
size_type oldSize = avail - data;
size_type newSpace = 2 * (limit - data);
if (newSpace == 0)
newSpace = 1; // Ensure that we have at least one slot.
iterator newData = new T[newSpace];
iterator p = newData;
for (const_iterator q = data; q != avail; ++q, ++p)
*p = *q;
delete [] data;
data = newData;
avail = data + oldSize;
limit = data + newSpace;
}
The algorithm that we use for increasing the size of a Vec has important implications for efficiency.
It is usually not possible simply to increase the size of a dynamic array, because the adjacent
memory may already be allocated. Consequently, if we have and area of M bytes and we want to
use N bytes, where M < N, we must: (1) allocate a new area of N bytes; (2) copy M bytes from the
old area to the new area; and (3) delete the old area. This operation requires time O(M).
If we add one element, or in fact any constant number of elements each time a Vec grows, the
performance of push_back will be quadratic. For example, if we add one element at each call of
grow, we will copy 1, then 2, then 3 elements. To get 4 elements into the Vec, we will have to copy
1 + 2 + 3 = 6 elements. To get N elements into the Vec, we will have to copy 12 N(N − 1) elements.
If, instead, we multiply the size of the Vec by a constant factor, the time spent copying falls to
O(N log N), which is much better. The implementation of grow in Figure 92 uses this technique
with a constant factor of 2.
We can improve the clarity of the implementation of Vec by doing some simple refactoring. Refac-
toring means rearranging code to improve it maintainability or performance without changing
its functionality. In this case, we introduce two overloaded versions of a private function called
create to manage the creation of new Vecs. We can use this function to simplify the code for
the constructors and the assignment operator. The two versions of create are declared in the
8 INHERITANCE AND TEMPLATES 157
template<typename T>
void Vec<T>::create(size_type n = 0, const T & val = T())
{
data = new T[n];
avail = data + n;
limit = avail;
for (iterator p = data; p != avail; ++p)
*p = val;
}
template<typename T>
void Vec<T>::create(const_iterator begin, const_iterator end)
{
size_type size = end - begin;
data = new T[size];
avail = data + size;
limit = avail;
for (iterator p = data; p != avail; ++p, ++begin)
*p = *begin;
}
The first version has two parameters, for the size of the array and the initial values, respectively.
Both parameters have default values, so that calling create() yields an empty Vec. The second
version also has two parameters that must be iterators defining a range of some other compatible
Vec.
The function create is responsible for allocating memory and for initializing the pointers data,
avail, and limit. Figure 93 shows the implementations of both versions. Figure 94 shows the
revised definitions of functions that use create. Finally, Figure 95 shows the declaration of class
Vec with all the changes that we have discussed.
It might seem from the example of class Vec that an iterator is just a pointer and that we can use
++, ==, and so on, just because these functions are defined for pointers.
In fact, this is not always the case. The STL class list, for example, stores data in a linked list of
nodes. An iterator value identifies a node. Incrementing the iterator means moving it to the next
node. As Figure 96 shows, achieving this requires defining all of the iterator functions, including *
and ->.
8 INHERITANCE AND TEMPLATES 158
In particular, note that the prefix operators --it and ++it are more efficient than the postfix
operators it-- and it++, because the postfix operators use the copy constructor to create the
result.
8 INHERITANCE AND TEMPLATES 159
private:
void create(size_type n = 0, const T & val = T());
void create(const_iterator begin, const_iterator end);
void grow();
iterator data;
iterator avail;
iterator limit;
};
const_iterator& operator++()
{ // preincrement
_Ptr = _Nextnode(_Ptr);
return (*this);
}
const_iterator operator++(int)
{ // postincrement
const_iterator _Tmp = *this;
++*this;
return (_Tmp);
}
const_iterator& operator--()
{ // predecrement
_Ptr = _Prevnode(_Ptr);
return (*this);
}
const_iterator operator--(int)
{ // postdecrement
const_iterator _Tmp = *this;
--*this;
return (_Tmp);
}
In any non-trivial program, there will come a time when things go wrong. There are several ways of
responding:
1. do nothing
2. report an error
6. throw an exception
The first four mechanisms are easy to implement and the fifth (triggering an assertion) was dis-
cussed in Section 2.7. The next section contrasts two approaches to coding, Section 9.2 discusses
the mechanics of exception handling, and Section 9.3 evaluates the appropriateness of the mecha-
nisms for various situations.
Error handling is an important topic. In large applications, as much as half of all the code may be
devoted to checking for errors. Moreover, this code is hard to get right. There can be real errors,
such as error reports getting lost or not being created in the first place, and inefficiencies caused
by repeated, unnecessary checks.
The function
returns a Matrix corresponding to a rotation that takes vector u to vector v. In other words, the
function returns a matrix M such that Mu = v.
The matrix computed by this function is correct only if u and v are unit vectors: |u| = |v| = 1. The
problem is what to do if u or v is not a unit vector.21
The first response is do nothing. We will assume that this is not an acceptable alternative because
the consequences could be serious. (Perhaps the rotation will be used to rotate an aircraft into the
correct orientation for landing.)
The second response is to specify that the vectors passed to the function must be unit vectors and
that the behaviour of the function is undefined if they are not. The usual way to do this is to write
an assertion or comment called a precondition in the code:
21
One obvious possibility would be to normalize the vectors before using them. We will asssume that, for some
reason, this is not a feasible solution for this application.
9 WHEN THINGS GO WRONG 162
/**
* Construct the matrix that rotates one vector to another.
* \param u is a vector representing an initial orientation.
* \param v is a vector representing the final orientation.
* The matrix, applied to \a u, will yield \a v.
* \pre The vectors \a u and \a v must be unit vectors.
*/
Matrix rotation(const Vector & u, const Vector & v);
The precondition passes the responsibility to the caller. Effectively, the comments define a contract
between the caller and the function: if you give me unit vectors, I will give you a rotation matrix;
if you give me anything else, I guarantee nothing. This form of coding is called design by contract
or DBC; it was pioneered by Bertrand Meyer (1997) but has been recommended by other people as
well (see, for example, (Hunt and Thomas 2000, pages 109–119)). The code for the function does
not check the length of the vectors u and v.
The third response is to have the function inspect the vectors and take some action if they are not
unit vectors:
This approach is called don’t trust the user or, more politely, defensive coding. We will discuss
possible ways of handling errors later.
There are advocates and opposers of both DBC and defensive coding. There is perhaps a general
trend away from defensive coding and towards DBC. For example, the home page for the Java
Modeling Language22 says that JML is a “design by contract” language for Java. Here are some
arguments for and against each approach.
Overhead DBC has no run-time overhead. Defensive coding executes tests which almost always
fail (e.g., most vectors passed to rotation are in fact unit vectors).
Safety DBC relies on programmers to respect contracts. Defensive coding ensures that malingerers
will be caught.
Clarity DBC requires maintainers to read comments. With defensive coding, the checks are in the
code.
Completeness There are situations that DBC cannot handle, such as the validity of user input. In
these situations, we can — and must — code defensively.
DBC and defensive programming are not mutually exclusive: you can use both. The best policy is
to decide which fits the needs of the particular application better and then use it.
22
http://www.cs.iastate.edu/∼leavens/JML/
9 WHEN THINGS GO WRONG 163
9.2 Exceptions
We have already seen a simple example of the use of exceptions in Section 7.6. The exception
handling mechanism of C++ provides one way of managing errors. It has two parts:
• The statement
throw hexpressioni
raises, or throws, an exception. The exception is the object obtained by evaluating hexpressioni.
• The statement
try
{
htry-sequencei
}
catch ( hexc-typei hexc-namei )
{
hcatch-sequencei
}
• The throw statement may not be visible in htry-sequencei: it may be (and usually is) nested
inside several levels of function call.
• Although we mentioned the “class” of the exception object, basic objects such as ints and
chars can be thrown as exceptions.
• There may be more than one catch clause. The run-time systems matches the exception
against each catch clause in turn, executing the first one that fits.
For example, suppose there is a class hierarchy Dog inherits Carnivore (meat-eater) inher-
its Animal and a try statement
try { dangerous_stuff }
catch (Dog d) { .... }
catch (Carnivore c) { .... }
catch (Animal a) { .... }
9 WHEN THINGS GO WRONG 164
try { dangerous_stuff }
catch (Animal a) { .... }
catch (Dog d) { .... }
catch (Carnivore c) { .... }
• The clause catch(...) (that is, you actually write three dots between parentheses) catches
all exceptions. If you use this in a multiple catch sequence, it should be the last catch
clause.
try
{
main();
}
catch (...)
{
fail();
}
so that unhandled exceptions terminate the program, usually with some more or less helpful
error message.
• If a catch-block discovers that it cannot handle the exception, it can execute throw (with
no argument) to pass the same exception to the next level.
• You can throw exceptions by value, or you can create an exception dynamically (using new)
and throw a pointer to it. If a pointer is thrown, the handler must delete the exception.
• When the run-time system reaches try, it pushes an exception frame onto the stack.23 This
frame contains descriptors for each catch clause.
23
An implementation may use a separate stack for exceptions. This stack will contain pointers to the main stack.
9 WHEN THINGS GO WRONG 165
• If the try-block executes normally, the exception frame is popped from the stack.
• If code in the try-block throws an exception, there will generally be a number of stack
frames on top of the exception frame. The run-time system moves down the stack, pop-
ping these frames and performing any clean-up actions required (e.g., calling destructors),
until it reaches the exception frame. This is called unwinding the stack.
• The run-time system inspects the catch descriptors until it finds a match. It then passes
the exception to the catch block and gives control to the catch block.
• When the catch block terminates, it passes control to the statement following the entire
try-catch sequence.
We have now discussed all of the possible responses (page 161) to a run-time problem. The next
step is to decide which one to use in a particular situation. We begin by characterizing the kind of
problems we are considering.
• If the problem is caused by a logical inconsistency in the program, the best way to deal with
it is to use DBC and/or assertions (or DBC with contracts expressed as assertions). It is not
appropriate to use if statements, error message, and the like to deal with simple incorrect-
ness.
Using the example above, suppose that the programmer(s) ensure that the function rotation
is always given unit vectors. If rotation receives a vector of the wrong length, there is a
logical error in the program that should trigger an assertion failure.
• If the problem is something that can reasonable be expected to happen, the best solution is
normal code. For example, an if statement to detect the condition followed by an appropri-
ate response.
Users cannot be relied upon to enter valid data. Any system component that is reading data
from the keyboard should validate the input and complain immediately if anything is wrong.
This does not require fancy coding techniques.
• The remaining are serious, rare, and unavoidable. The following subsections discuss suitable
responses to problems of this kind.
The easiest response to a problem is an error message, sent to cout, or (better) cerr, or, in a
windowing environment, a dialog or message box.
The streams cout and cerr behave in essentially the same way. Both send messages to a stream
that C++ calls standard output. he difference is that cout is buffered and cerr is not. When the
programs crashes, it is more likely to have displayed cerr output than cout output.
If this method works for your application, use it. However, it is inappropriate for many applications:
9 WHEN THINGS GO WRONG 166
• The software may be embedded in a car, pacemaker, or electric toaster. There is nowhere to
send messages to and perhaps no one to respond to them anyway.
• The software is part of a system that must do its job as well as possible without giving up or
complaining. For example, an internet router.
• The user is not someone who can handle the problem. For example, a web browser should
not display error messages — although, of course, they sometimes do — because there isn’t
much typical users can do.
An effective system used by many software packages, such as unixTM and OpenGL, is to set an
error flag and continue in the best feasible way.
• A unixTM library function may set the global variable errno. Most library functions also do
something else to indicate failure, such as returning -1 instead of a char.
• Many OpenGL functions perform according to the following specification: either the function
behaves as expected, or an error number is set and there is no other effect.
This system requires some discipline from the programmers using it. They should look at the error
status from time to time to make sure that nothing has gone wrong. A common strategy is to ignore
the error status except just after doing something that is likely to fail.
Error codes are ideal for an application in which the consequences of failures are usually not seri-
ous, such as a graphics library. They are not secure enough for safety-critical applications.
A function can return a funny value to indicate that it has not completed its task successfully. We
will call these values special return values. The classic example of this behaviour is the C function
getchar: you would expect its type to be char or even unsigned char, but in fact it returns
an int (thus causing much grief to C beginners). It does this so that it can report end-of-file by
returning -1.
Special return values are easy to code and require no special language features. They have strong
advocates.24 They also have disadvantages:
• There may be no suitable value to return. This is not a problem for exp and log, whose
values are always positive, but how does tan report an error (its range is all of the reals from
−∞ to ∞)?
• In some cases, it is not feasible to pack all of the information about errors and returned data
into a single value. Then we have to add reference parameters to the function to enable it to
return all of the information.
24
Graduate student Ravi Rao drew my attention to an interesting article by Joel Spolsky that argues for special return
values rather than exceptions: http://joelonsoftware.com/items/2003/10/13.html.
9 WHEN THINGS GO WRONG 167
int ch;
while ( ch = getchar() >= 0 )
{
// process characters
}
// end of file
double t1 = h(x);
if (t1 == h_error_value)
// handle h_error
else
{
double t2 = g(t1);
if (t2 == g_error_value)
// handle g_error
else
{
double y = f(t2);
if (y == f_error_value)
// handle f_error
else
{
// carry on
}
}
}
• Using the return value for multiple purposes leads to awkward code. In particular, conditions
with side-effects are often needed, as in the C idiom of Figure 97.
• Code can become verbose. Instead of writing y = f(g(h(x))), we have to write some-
thing like the code in Figure 98.
• Programmers have a tendency not to check for special return values. This problem is notori-
ous in unixTM .
• The caller may not know how to handle the problem. There will be multiple levels of func-
tions, all specially coded to return funny results until someone can deal with the situation
appropriately.
9 WHEN THINGS GO WRONG 168
9.3.4 Exceptions
Exceptions provide a form of communication between distant parts of a program. The problem that
exceptions solve is: something has gone wrong but, at this level or in this context, there is no way
to fix it. Examples:
• In the middle of complex fluid-flow calculations, the control system software of a nuclear
reactor detects that a pressure is sending improbable data.
• A library function that has a simple, natural interface (e.g., Matrix::invert) but may
nevertheless fail for some inputs (e.g., singular matrix).
The main advantage of exceptions is that they can transfer control over many levels without clut-
tering the code. Unfortunately, this is also their main disadvantage. The sequence
make_a_mess();
clean_up_mess();
looks perfectly fine until you realize that make_a_mess might throw an exception.
• The thrower does not have to know where the catcher is.
• The catcher does not have to know where the thrower is.
• If no exceptions are thrown, the overhead of the exception handling system is essentially
zero.
• The try and throw statements make it obvious in the code that a problem is being detected
and handled.
• A programmer who calls a function that might throw an exception, either directly or indirectly
(i.e., at some deeply nested place) cannot rely on that function to return. (This is sometimes
called “the invisible goto problem”.)
• Exceptions violate the “one flow in, one flow out” rule.
• It may be difficult for maintenance programmers to match corresponding try and throw
statements. (The first problem is “who threw this?” and the second problem is “where is this
going to end up?”.)
Exception-safe coding is an important topic for C++ programmers, but a rather large one for this
course. Herb Sutter (2005) devotes 44 pages to it. The basic rules are:
• Write each function to be exception safe, meaning that it works properly when the functions
it calls raise exceptions.
• Write each function to be exception neutral, meaning that any exceptions that the function
cannot safely handle are propagated to the caller.
As an example, the constructor of the class Vec, discussed in Section 8.4, is exception-safe. Here
is the code again:
The only action that may cause an exception to be thrown is new, because the default allocator
throws an exception when there is no memory available. The constructor does not handle this
exception but, by default, passes it on to the caller. Therefore the constructor is exception neutral.
The remaining danger is that the constructor does not work properly when the exception is raised.
For example, it might happen that the pointers are set even though no data has been allocated. This
doesn’t matter, because a constructor that raises an exception is assumed to have failed completely.
There is no object, and so values of the attributes of the object are irrelevant.
9 WHEN THINGS GO WRONG 170
template<class T>
T Stack<T>::pop()
{
if (vused_ == 0)
{
throw "Popping empty stack";
}
else
{
T result = v_[used_ - 1];
--vused_;
return result;
}
}
template<class T>
void Stack<T>::pop(T & result)
{
if (vused_ == 0)
{
throw "Popping empty stack";
}
else
{
result = v_[used_ - 1];
--vused_;
}
}
So far so good. Now consider a case where there is a problem. The code in Figure 99 is supposed
to implement “popping” a stack (Sutter 2005, page 34). The subtle problem with this code is that
return result requires a copy operation that may fail and throw an exception. If it does, the
state of the stack has been changed (--vused_) but the popped value has been lost. The code in
Figure 100 avoids this problem:
The STL is exception-safe. In order to avoid problems like these, it provides two functions for
popping a stack:
const T & stack::top() const returns the top element of the stack
Another rule that is provided and assumed by the STL is: destructors do not throw exceptions.
10 SYSTEM DESIGN 171
10 System Design
For large systems, design must take into account not only the performance of the finished product,
but also its development and maintenance. Three anecdotes (the first two from John Lakos’s (1996)
experiences) illustrate the problems of large-scale development.
TargetID id;
After a quick search failed, he tried using the unixTM utility grep to search for the string
"TargetID". There were several thousand header files involved, and grep complained
“too many files”. The programmer wrote a script to search through a*.h, then b*.h, and
so on. This search eventually revealed
2. Lakos worked at Mentor Graphics, a company that developed one of the first general-purpose
graphics libraries for unixTM systems. Programmers were in the habit of #includeing all
of the headers that they thought their component might need. The result was that compiling
the library required more than a week — using a network of workstations.
3. A major software product was completed, the source code and executables were written to
CDs, and the product was ready to be shipped to the customer. A couple of days later, a
programmer made a small change to a member function, something like this:
class Widget
{
public:
double get()
{
++accessCount; // this line added
return size;
}
private:
static double size;
unsigned long accessCount;
};
Widget *pw;
// .... several pages of code
s = pw->get();
10 SYSTEM DESIGN 172
Object oriented logical design concerns the organization of classes from the point of view of func-
tionality, inheritance, layering, and so on. It is discussed in many books on C++ programming and
software engineering, often with the use of UML diagrams, patterns, and other aids.
Physical design concerns the distribution of the various classes and other entities into files, direc-
tories, and libraries. Physical design is important for large projects but is less often discussed in
books (Lakos (1996) being a significant exception).
Logical and physical design are closely related. If the logical design is bad, it will not usually be
possible to obtain a good physical design. But a good logical design can be spoilt by a poor physical
design.
Logically, a system consists of classes (including enumerations) and free functions, with classes
providing the main structure.
Physically, a system consists of components. There are various ways of defining components but,
fortunately, there is one precise definition which is suitable for systems written mostly or entirely
in C++.
The header and implementation files may both use #include to read other files. However, these
other files are not considered to be part of the component.
The compiler turns each component into an object file (.obj) or sometimes a library file (.lib or
.dll). The linker takes all the object and library files and creates an executable. Components
are also called compilation units (see Section 1.2.1) and translation units.
Since C++ does not allow a class declaration to be split over several files, the definition of component
implies that every class belongs to exactly one component. However, the definition does allow a
component to contain more than one class and, in fact, it is often useful to define components with
several classes:
• A class, or classes, needed by a single component can be declared in the implementation file
of that component.
In general, the logical structure of a design is determined by its classes; the physical structure of a
design is determined by its components.
There are various kinds of logical association between two classes: a class can contain an instance
of another class or a pointer to such an instance; inherit another class; have a value of another class
passed to it by value, reference, or as a pointer; and so on. Physical associations are, in general,
simpler: one component either uses another component or it doesn’t.
A client of component C is another component of the system that uses C. With a few exceptions
(see Figure 10.4.2), clients can be recognized because they #include header files: component C1
is a client of C2 if either C1.h or C1.cpp needs to read C2.h. Note that:
10 SYSTEM DESIGN 173
• “Reading” C2.h is not the same thing as #includeing C2.h because a client might #include
X.h which #includes C2.h. In Figure 101, compiling C1.cpp requires reading C2.h:
• The client relationship is transitive: if C1 is a client of C2, and C2 is a client of C3, then C1
is a client of C3.
10.2 Linkage
We discussed linkage issues previously (see Section 4.3). To get good physical structure, we want
to minimize dependencies between components. Doing this requires knowing how dependencies
arise.
Declarations in a header or implementation file have no effect outside the file (except, of course,
that declarations in a header file are read in the corresponding implementation file).
Definitions in a header or implementation file cause information to be written to the object file, and
therefore create dependencies. As we have seen, definitions should be avoided altogether in header
files.
General rules:
• Put only constant, enumeration, and class declarations into header files.
The compiler considers inlined functions to be declarations, not definitions, even if they have bod-
ies. It is therefore acceptable to put, for example,
in a header file. However, if you remove the inline qualifier, the program may not compile! This
is because the header file may be read more than once, putting two copies of the function sqr into
the program, which causes problems for the linker.
10 SYSTEM DESIGN 174
10.3 Cohesion
Every book on Software Engineering includes the slogan low coupling, high cohesion. This mantra
is useful only if we know:
• what is coupling?
• what is cohesion?
Coupling is probably the more important of these two aspects of a system, and we discuss it in
Section 10.4.
Cohesion is the less important partner of the “low coupling, high cohesion” slogan. Roughly speak-
ing, a component is cohesive if it is independent of other components (as far as possible) and per-
forms a single, well-defined role, or perhaps a small number of closely related tasks. A component
is not cohesive if its role is hard to define or if it performs a variety of loosely related tasks.
One way to define cohesion is by saying that the capabilities of a class should be necessary and
sufficient (like a condition in logic). The capabilities of a component are necessary if the system
cannot manage without it. The capabilities of a class are sufficient if they jointly perform all the
services that the client requires.
The “necessary and sufficient” criterion is not the whole story. For example, we could write the
entire system as one gigantic class that provided the required functionality and had no superfluous
functions; clearly, this class would be both necessary and sufficient, but it would also be unman-
ageable and probably useless.
Sufficiency is a precise concept, but there is some leeway. For example, if it turns out that the
sequence
p->f();
p->g();
occurs often in system code — perhaps, in fact, every invocation of f is followed by a call to g —
then it probably makes sense to add a function h that combines f and g to the class. The old class
was technically sufficient, but the new function improves clarity, simplifies maintenance, and may
even make the program run a little faster.
Clearly there is no point in taking the time to code and test functions that will never be used.
Nevertheless, there are programmers who like to spend large amounts of time writing code that
“might be useful one day” rather than focusing on writing or improving code that was actually
needed yesterday.
10 SYSTEM DESIGN 175
Consequently, cohesion also implies a division of the system into components of manageable size.
A good guideline is that it should be possible to describe the role of a component with a single
sentence. If you ask what a component does and the answer is either a mumble or a 10 minute
peroration, there is probably something wrong with the design of the component.
Cohesion is related to coupling in the following way: a component that tries to do too much (that
is, plays several roles) is likely to have many clients (perhaps one or more for each role). It may
also need to be a client of several other components in order to perform its roles. Consequently, its
coupling is likely to be high. On the other hand, a cohesive component is likely to have few clients
and few dependencies, and therefore lower coupling.
• Low cohesion in the design can sometimes be corrected by careful physical design. For exam-
ple, a group of related classes could be put into a single component, exposing on some class
interfaces to the rest of the system.
10.4 Coupling
Coupling is not an all-or-nothing phenomenon: there are degrees of coupling. At one end of the
scale, if a component has no coupling with the rest of the system, it cannot be doing anything
useful and should be thrown away. It follows that some coupling is essential and therefore that the
issue is reducing coupling, not eliminating it.
The other end of the scale is very high coupling: every component of the system is strongly coupled
to every other component. Such a system will be very hard to maintain, because a change to one
component often requires changes to other components.
10.4.1 Encapsulation
The first step towards low coupling is encapsulation, which means hiding the implementation de-
tails of an object and exposing only a well-defined public interface. Figure 102 shows is a first
(rather feeble) attempt at defining a class for points with two coordinates.
Class Point1 provides very poor encapsulation: anyone can get and set its coordinates, and it has
no control over its state at all. Obviously, we should make the coordinate data private, but then
we would have to provide some access functions, as shown in Figure 103.
Access functions that provide no checking, like these, are not much better than public data.
But access functions to at least provide the possibility of controlling state and maintaining class
invariants. For example, setX might be redefined as
10 SYSTEM DESIGN 176
class Point1
{
public:
double x;
double y;
};
class Point2
{
public:
double getX() { return x; }
double getY() { return y; }
void setX(double nx) { x = nx; }
void setY(double ny) { y = ny; }
private:
double x;
double y;
};
Access functions provide a way of hiding the representation of an object. For example, Figure 104
shows how we could define points using complex numbers without affecting users in any way
(except, perhaps, efficiency).
Even with access functions, however, Point hardly qualifies as an object. Why do users want
points? What are the operations that points should provide? A class for points should look more
like Figure 105, in which function declarations appear in the class declaration, but function defini-
tions are in a separate implementation file.
Point4 has less coupling than Point3 in another respect. If any of the inline functions of
Point3 are changed, its clients will have to be recompiled. Since the functions of Point4 are
defined in Point4.cpp rather than Point4.h, they can be changed without affecting clients
(although the system will have to be re-linked, of course).
A client of one of the Pointn classes will be coupled to the Pointn component. The degree of
coupling depends on the Point class: it is highest for Point1 (the user has full access to the
coordinates) and lowest for Point4 (the user can manipulate points only through functions such
as move and draw).
10 SYSTEM DESIGN 177
class Point3
{
public:
double getX() { return z.re; }
double getY() { return z.im; }
void setX(double nx) { z.re = nx; }
void setY(double ny) { z.im = ny; }
private:
complex<double> z;
};
class Point4
{
public:
void draw();
void move(double dx, double dy);
....
private:
// Hidden representation
};
From the point of view of the owner of the Point class, lower coupling means greater freedom.
If the owner of Point1 makes almost any change at all, all clients will be affected. The owner
of Point4, on the other hand, can change the representation of a point, or the definitions of the
member functions, without clients needing to know, provided only that the class continues to meet
its specification. This is one advantage of low coupling:
A complicated object is entitled to have a few access functions but, in general, a class should keep a
secret.25 If your class seems to need a lot of get and set functions, you should seriously consider
redesigning it.
Here are formal definitions (Lakos 1996, pages 105 and 138):
2. An implementation entity (type, variable, function, etc.) that is not accessible or detectable
programmatically through the logical interface of a component is encapsulated by that com-
ponent.
25
The useful metaphor “keeping a secret” was introduced by David Parnas in a very influential paper (1978).
10 SYSTEM DESIGN 178
IC ∪ EC = U and IC ∩ EC =
where IC is the set of implementation entities in the logical interface of C, EC is the set of entities
encapsulated by C, and U is the “universe” of all entities in C.
C++ provides various ways in which coupling between components can be hidden: that is, there is
a dependency between two components even though neither #includes the other’s header file.
For example, the following components A and B are coupled:
.... ....
Using the definitions of the previous section, we note that numWidgets is in the logical interface
of component A, because it can be accessed by component B by using extern.
The object file obtained when A.cpp is compiled will allocate memory for numWidgets. The
object file obtained when B.cpp is compiled will not allocate memory for numWidgets but will
expect the linker to provide an address for numWidgets. If the definition in A.cpp is changed
or removed, both components will compile, but the system won’t link.
Coupling can affect the time needed to rebuild a system. Build times are significant for large
projects, and it is useful to know how to keep them low. If we define class Point5 as in Figure 106,
sizeof(Point5) gives 16 bytes, showing that the compiler allocates two 8-byte double values
to store a Point5. If we decide to add a new data member, d, to store the distance of the point
from the origin, we obtain Point6, shown in Figure 107. Then sizeof(Point6) gives 24 bytes,
showing that the compiler allocates three 8-byte double values to store a Point6.
At this point, we might decide that our class needs a function, as shown in Figure 108. Adding a
function has no effect on the size of the class: sizeof(Point7) is 24 bytes, just like Point6.
But if we make the function virtual, as in Figure 109, then sizeof(Point8) gives 32 bytes,
because a virtual function requires a virtual function table or vtable for short.26
26
The pointer to the vtable needs 4 bytes on the Intel architecture. The additional 4 bytes may be added for alignment
purposes.
10 SYSTEM DESIGN 179
class Point5
{
private:
double x;
double y;
};
class Point6
{
private:
double x;
double y;
double d;
};
class Point7
{
public:
void move(double dx, double dy) { x += dx; y += dy; }
private:
double x;
double y;
double d;
};
class Point8
{
public:
virtual void move(double dx, double dy) { x += dx; y += dy; }
private:
double x;
double y;
double d;
};
#include "point.h"
int main()
{
Point p;
....
}
#include "point.h"
int main()
{
Point* pp;
....
void f(Point & p);
....
}
In summary, adding or removing data members changes the size of the objects. Adding a virtual
function also changes the size. (Adding virtual functions after the first makes no difference, because
there is only one vtable and it contains the addresses of all virtual functions.)
The changes we have been discussing should not affect users of the class. Private data members
cannot be accessed anyway, and whether a function is virtual affects only derived classes. Neverthe-
less, if we change the size of a point, every component that includes point.h will be recompiled
during the next build! Since building a large project can take hours or even days, changing a class
declaration, even the private part, is something best avoided.
To see why this happens, consider the first program in Figure 110. To allocate stack space for p, the
compiler must be able to compute sizeof(Point). To compute this, it must see the declaration
of class Point. Finally, to see the declaration, it must read "point.h". If "point.h" changes,
the program must be recompiled.
The program in Figure 111 is slightly different. The compiler does not need to know sizeof(Point)
to compile this program, because all pointers and references have the same size (the size of an ad-
dress: usually 4 bytes). Consequently, reading the declaration of class Point is a waste of time.
However, the compiler does need to know that Point is a class and, for this purpose, the forward
declaration of Figure 112 is sufficient.
Don’t include a header file when a forward declaration is all you need.
In early versions of the standard libraries, names such as ostream referred to actual classes.
Consequently, the code shown in Figure 113 worked well in a header file. Times have changed, and
10 SYSTEM DESIGN 181
int main()
{
Point* pp;
....
void f(Point & p);
....
}
class ostream;
....
friend ostream & operator<<(ostream & os, const Widget & w);
ostream is now defined by typedef. However, the standard library defines a header file that
contains forward declarations for all stream classes: see Figure 114.
Suppose that points have colours. It is tempting to put the enumeration declaration outside the
class declaration:
class Point
{
....
This is convenient, because we can use the identifiers RED, GREEN, and BLUE wherever we like.
But this convenience is also a serious drawback: the global namespace is polluted by the presence
of these new names. It is much better to put the enumeration inside the class declaration, like this:
class Point
{
public:
enum Colour { RED, GEEN, BLUE };
....
#include <iosfwd>
....
friend ostream & operator<<(ostream & os, const Widget & w);
We now have to write Point::RED instead of RED, but there is no longer any danger of the colour
names clashing with colour names introduced by someone else.
In situations where class declarations alone are inadequate, for example in the development of a
library, we can use namespaces instead.
The worst kind of dependencies are cyclic dependencies. When a system has cyclic dependencies,
“nothing works until everything works”.27 Some cyclic dependencies are unavoidable, but many
can be eliminated by careful design.
Suppose we have classes Foo and Bar that are similar enough to be compared. We might write
class Foo
{
public:
operator==(const Bar * b);
....
};
class Bar
{
public:
operator==(const Foo & f);
....
};
This creates a cyclic dependency between Foo and Bar. The dependency can be eliminated by
using friend functions:
class Foo
{
friend operator==(const Foo & f, const Bar & b);
friend operator==(const Bar & b, const Foo & f);
....
};
class Bar
{
friend operator==(const Foo & f, const Bar & b);
friend operator==(const Bar & b, const Foo & f);
....
};
10.4.5 Pimpl
A complicated class might have quite a large private part. Every time the owner of the class
changes the class declaration, every client gets recompiled. A “pimpl” is a simple way of avoiding
this dependence: it is a mnemonic for pointer to implementation. Thus
class Widget
{
public:
....
private:
int something;
char somethingElse;
double yetAnotherThing;
....
};
becomes
class Widget
{
public:
....
private:
class WidgetImplementation;
WidgetImplementation * pimpl;
};
There is naturally a price to pay for the increased indirection: the functions of Widget are reduced
to messengers that just forward their requests to WidgetImplementation:
class Widget
{
public:
Widget() { pimpl = new WidgetImplementation(); }
~Widget() { delete pimpl; }
int getSomething() { return pimpl->getSomething(); }
void doSomething(char what) { pimpl->doSomething(what); }
....
private:
WidgetImplementation * pimpl;
};
The overhead of the extra calls will be small, possibly even zero. For a large system, however,
the gains may be considerable. The owner of WidgetImplementation can change data and
functions freely without forcing recompilation of Widget clients. In fact, Widget clients will be
recompiled only if the declaration of class Widget itself has to be changed, perhaps by adding a
new function. Herb Sutter (2000, page 110) says:
10 SYSTEM DESIGN 184
Another name for pimpl is “handle/body class”. In the example, above, Widget is the han-
dle and WidgetImplementation is the body. Koenig and Moo (2000) use this term: Sec-
tion 13.4 (pp. 243–245) gives a definition of class Student_info in which the only data member
is Core *cp. The pointer cp points an instance of either the base class Core or the derived class
Grad, illustrating a further advantage of pimpl: a class may provide behaviour that depends on
the way in which it is initialized.
10.4.6 Inlining
Normally, a function is called by evaluating its arguments, placing them in registers or on the stack,
storing a return link in the stack, and passing control to the function’s code. When the function
returns, it uses the return link to transfer control back to the call site. There is clearly a fair amount
of overhead, especially if the function is doing something trivial, such as returning the value of a
data member of a class.
If the compiler has access to the definition of a function, it can compile the body of the function
directly, without the call and return. This is called inlining the function.
An inline function will usually be faster than a called function, although the difference will be
significant only for small functions. (For large functions, especially if they have loops or recursion,
the time taken by calling and returning will be negligible compared to the time taken to execute the
function.)
Heavy use of inlined functions increases the size of the code, because the code of the function is
compiled many times rather than once only. Thus inlining is an example of a time/space tradeoff.
Inlining is relevant to this section because inlining affects coupling. The compiler can inline a
function only if its definition is visible. Within an implementation file, a definition of the form
permits the compiler to inline f, but only in that particular implementation file. To inline a func-
tion throughout the system, the inline qualifier, and the body of the function, must appear in a
header file. As we have seen, this implies that any change to the function body will force recompi-
lation of all clients.
Whenever a function definition appears inside a class declaration, the compiler is allowed to compile
it inline. In Figure 115, the compiler may inline f1 and f3 and it cannot inline f2 and f4.
The qualifier inline is a compiler hint, not a directive. The compiler is not obliged to inline func-
tions that are defined inside the class declaration or declared inline, and it may inline functions
of its own accord.
Do not place too much dependence on inlining: the rewards are not great and there may be draw-
backs. Herb Sutter (2002, pages 83–86) argues that good compilers know when and when not to
inline and programmers should leave the choice to them.
10 SYSTEM DESIGN 185
#ifndef WIDGET_H
#define WIDGET_H
class Widget
{
public:
int f1() { return counter; }
int f2();
private:
int counter;
};
char f4();
There are several techniques for developing well-structured systems or improving systems with
structural weaknesses.
CRC cards where introduced by Kent Beck and Ward Cunningham at OOPSLA (1989) for teaching
programmers the object-oriented paradigm. A CRC card is an index card that is use to represent the
responsibilities of classes and the interaction between the classes. The cards are created through
scenarios, based on the system requirements, that model the behavior of the system. The name
CRC stands for Class, Responsibilities, and Collaborators.
Although CRC cards are old and have largely been replaced by heavy-weight methods such as UML,
the underlying ideas are still useful in the early stages of system design. The focus on responsibility
and collaboration is appropriate and helps to improve the coupling/cohesion ratio.
10.5.2 Refactoring
10.5.3 DRY
DRY stands for don’t repeat yourself. As systems grow, it is easy for them to accumulate multiple
implementations of a single function. These functions might vary in small details, such as the
number and order of parameters, but they do essentially the same thing. Weed out such repetition
by converting all the variations into a single function whenever you can. As Hunt and Thomas
(2000, page 27) say:28
10.5.4 YAGNI
YAGNI stands for you aren’t going to need it and it is a slogan associated with agile methods. Some
programmers are tempted to provide all kinds of features that might come in useful one day. When
writing a class, for instance, they will include a lot of methods but they don’t actually need right
now for the application, but look nice. This is usually a waste of time: there is a good chance that
the functions will not in fact be needed and, if they are, it does not take long to write them.
Patterns (Gamma, Helm, Johnson, and Vlissides 1995)29 belong more to high-level design than to
physical organization. However, interesting issues arise in mapping patterns to concrete C++ code,
and this section describes some of these issues.
10.6.1 Singleton
GoF summarizes the Singleton pattern as: ensure a class has only one instance, and provide a global
point of access to it.Figure 116 shows a declaration for class Singleton based on (Alexandrescu
2001, pages 129–133). Here are some points of interest in this declaration.
• The function fun and the data member uid are included just to illustrate that the singleton
can do something besides merely exist.
• The only way that a user can access the singleton is through the static reference function
instance.
• Access to the unique instance of the singleton is through private, static pointer, pInstance.
• The copy constructor and assignment operator are private and unimplemented. This en-
sures that the singleton cannot be passed by value, assigned, or otherwise copied.
28
I changed their word “single” to “unique” for greater emphasis.
29
The four authors of this book are often referred to as “the Gang of Four”. Like other authors, we will refer to the
book as “GoF”.
10 SYSTEM DESIGN 187
• The destructor is also private and unimplemented. This ensures that the singleton cannot
be accidentally deleted. (This could be considered as a memory leak, but that is harmless
because there is only one instance anyway.)
class Singleton
{
public:
static Singleton & instance();
void fun();
private:
int uid;
static Singleton * pInstance;
Singleton();
Singleton(const Singleton &);
Singleton & operator=(const Singleton &);
~Singleton();
};
Figure 117 shows the implementation of class Singleton. The constructor is conventional; the
body given here merely demonstrates that it works. The function instance constructs the sin-
gleton when it is called for the first time, and subsequently just returns a reference to it.
Singleton::Singleton()
{
uid = 77;
cout << "Constructed Singleton " << uid << endl;
}
void Singleton::fun()
{
cout << "I am Singleton " << uid << endl;
}
Singleton * Singleton::pInstance = 0;
The following code demonstrates the singleton in action. A user must access the singleton as
Singleton::instance(). Any attempt to copy it or pass it by value causes a compile-time
error. For the particular singleton defined here, all the user can do is apply the function fun to the
singleton.
int main()
{
Singleton::instance().fun();
Singleton::instance().fun();
Singleton::instance().fun();
return 0;
}
This is in fact a rather simple version of the Singleton pattern and it is not robust enough for all
applications. For details about its improvement, see (Alexandrescu 2001, pages 133–156)
10.6.2 Composite
The composite pattern is used with part-whole hierarchies. A simple hierarchy allows the user to
work with one part at a time. The composite pattern allows the user to work also with groups of
parts as if they were single parts.
The example is a highly simplified typesetting application. The abstract base class Text has a
single, pure virtual function set which “sets” type to an output stream provided as a parameter.
Initially, there are three derived classes, Blank, Character, and Word, as shown in Figure 118.
Suppose that we want to typeset paragraphs. Paragraphs are related to the classes we have in
that they should be able to implement the method set, but they are also different in that a para-
graph has many words and is typically typeset between margins. Nevertheless, we can add a class
Paragraph to the hierarchy, as shown in Figure 119.
Class Paragraph has a parameter in the constructor giving the width in which to set the para-
graph. (A more realistic example would also allow this value to be set after construction.) We
provide a function addWord that allows us to build paragraphs, and the words are stored in a
STL vector. The important points are that class Paragraph inherits from class Text and
implements set, making it a part of the hierarchy.
Figure 120 shows the implementation of the Paragraph functions set and addWord. Function
set uses a stringstream to store the words in a line. When there is not enough space on the
line for the next word (and the blank that precedes it), the string stream buffer is written to the
output stream.
10.6.3 Visitor
Each time we add a function to a class hierarchy such as Text, we have to add one function to each
class in the hierarchy. Furthermore, each of these functions has essentially the same structure. For
example, every function we add to class Paragraph will iterate over the words in the paragraph.
10 SYSTEM DESIGN 189
class Text
{
public:
virtual void set(std::ostream & os) = 0;
};
The purpose of the visitor pattern is to avoid both the need to add functions to every class and to
repeat the iteration patterns over and over again. The idea is to define a “visitor” class that knows
how to process each kind of object in the hierarchy. The visitor class is an abstract base class that
cannot actually do anything useful, but it has derived classes for performing specific operations.
The following steps are required to support visitors in the text hierarchy.
1. Create a base class Visitor with a visiting function corresponding to each derived class in
the Text hierarchy: see Figure 121. Each visiting function is passed a pointer to an object of
the corresponding type in the Text hierarchy.
2. Add functions to “accept” visitors in the Text hierarchy, starting with a pure virtual function
in the base class:
class Text
{
public:
virtual void accept(Visitor & vis) = 0;
....
};
10 SYSTEM DESIGN 191
class Visitor
{
public:
virtual void visitBlank(Blank*) = 0;
virtual void visitCharacter(Character*) = 0;
virtual void visitWord(Word*) = 0;
virtual void visitParagraph(Paragraph*) = 0;
};
For composite classes, function accept passes the visitor to each component individually:
3. The next step is to construct an actual visitor. We will reimplement the typesetting func-
tion, set as a visitor. For this, we need a class setVisitor derived from Visitor: see
Figure 122.
void setVisitor::visitBlank(Blank*)
{
cout << ’ ’;
}
p.accept(setVisitor());
For a single task (typesetting), setting up the visitor classes seems rather elaborate. Suppose, how-
ever, that there were many operations to be performed on the Text hierarchy. Once we have
defined the accept functions, we do not need to make any further changes to that hierarchy. In-
stead, for each new operation that we need, we derive a class from Visitor and define its “visit”
functions for each kind of Text.
• If we use a separate function for each operation (like set in the original example), we can
pass information around simply by adding parameters. Since the operations are independent,
each can have its own set of parameters.
The operations in the visitor version, however, must all use the protocol imposed by accept.
This means that they all get exactly the same parameters (none, in our example).
• The structure of composite objects is hard-wired into their accept functions. For example,
Paragraph::accept iterates through its vector of Words. This makes it difficult to
modify the traversal in any way.
In this example, Paragraph::set inserted line breaks whenever the length of a line would
otherwise have exceeded width. It is difficult to provide this behaviour with the visitor
pattern, because Paragraph::accept does a simple traversal over the words and does
not provide for any additional actions.
11 POTPOURRI 193
11 Potpourri
This chapter is a small selection of topics that cannot be covered in depth because time has run
out.
This section describes the application of some of the concepts developed into this course to the
development of a simple compiler.
Scanning The first task of a compiler is to read the source code. It is usually best to start by
discarding white space and comments and assembling the rest of the text into tokens that are
meaningful to the compiler. Some tokens are single characters (e.g., (, ;, *) but most tokens
consist of several characters: keywords, identifiers, and literals of various kinds. Information about
a token is stored in an instance of class Token. The variable line stores the number of the source
code line containing the token and is used for reporting errors.
class Token
{
public:
// ....
private:
int line;
TokenKind kind;
std::string value;
int left;
int right;
};
TokenKind is an enumeration of the different kinds of token. Each keyword of the language has
a different kind. When the compiler encounters a string of letters in the source code, it needs to
know whether it is a keyword. If it isn’t a keyword, it’s an identifier. The STL class map provides a
simple way of checking for keywords:
Converting source code into tokens is performed by the scanner. A scanner can be written to return
tokens one at a time, but it is easier to scan the entire source text and return a list of tokens. Class
Scanner provides a function that reads a file and returns the tokens in it:
Parsing The parser uses the grammar of the language to construct an abstract syntax tree from
the tokens. It has the list of tokens provided by the scanner and uses an iterator of this list to
provide access to individual tokens.
class Parser
{
public:
// ....
private:
std::list<Token> tokens;
std::list<Token>::const_iterator tki;
};
The parser has one function for each non-terminal of the grammar. Each parsing function returns
a pointer to ASTNode, which is the abstract base class of the syntax tree nodes. For convenience,
the compiler defines
Figure 124 shows part of a parsing function. Note the use of tki to access parts of the current
token and ++tki to move to the next token.
The parse tree nodes are mutually recursive. For example, conditional statements and loop state-
ments contain lists of statements. These lists are stored in instances of class SequenceNode,
shown in Figure 125.
Semantic Actions Figure 125 also shows some of the functions used to process the syntax tree:
All of these functions are defined as virtual in the base class. Many of them are just simple
recursive calls to implementations of the same function in other nodes, as in this example:
Node Parser::parseStatement()
{
Node result = 0;
switch (tki->kind)
{
case KW_EXIT:
result = new ExitNode(tki->line);
++tki;
break;
case IDENVAL:
{
int line = tki->line;
Node target = parseTerm();
Node expr = 0;
switch (tki->kind)
{
case OP_ASSIGN:
{
++tki;
ModeType mode = parseMode();
if (isExpression())
expr = parseExpression();
result = new AssignNode(line,
target, mode, expr);
}
break;
}
// ....
}
return result;
}
The Virtual Machine The compiler generates code for a virtual machine (VM). Data in the VM is
represented by a class hierarchy with a base class Datum and derived classes for various kinds of
data:
class Datum
class BoolDatum
class CharDatum
class TextDatum
class IntDatum
class RecDatum
class PortDatum
class ConPortDatum
11 POTPOURRI 196
class KbdPortDatum
The memory of the virtual machine is a vector of pointers to Datum objects. The class Memory also
provides access to the memory and various other operations: see Figure 126. As usual, we need two
functions for memory reference: a const version to read from memory and a non-const version
to write to memory.
The VM has a different kind of memory for instructions. Each entry in this kind of memory is
an instance of Instruction. An instruction has the line number of the source code statement
that generated it, an opcode represented by an enumeration value, and up to three arguments. An
Address is an index into the memory vector defined above.
class Instruction
{
public:
// ....
private:
int line;
Codes opcode;
Address args[3];
};
Code Generation Object code is generated by calling root->gen(), where root is the root of
the syntax tree. The various versions of gen call one another recursively, and when they have some
actual code to generator, they invoke the code generator.
The code generator is an object that provides a number of functions for generating code. Here is a
11 POTPOURRI 197
class Memory
{
public:
Datum * & operator[](Address addr)
{
return mem[addr];
}
Datum * const & operator[](Address addr) const
{
return mem[addr];
}
Address nextFree() { return mem.size(); }
void makememory(Index max)
{
while (mem.size() < max)
mem.push_back(0);
}
friend ostream & operator<<(ostream & os, Memory & m);
private:
vector<Datum*> mem;
};
typical function that generates a jump instruction. The table entries stores information about
jump instruction addresses and destinations. The vector code stores the generated object code.
void CodeGenerator::genConditionalJump(
int line, Index ix, Address expr, bool cond)
{
entries[ix].addJump(code.size());
if (cond)
code.push_back(Instruction(line, JPT, 0, expr));
else
code.push_back(Instruction(line, JPF, 0, expr));
}
Figure 127 shows the classes responsible for jump information and code generation. Class LabelEntry
uses a list of addresses to store the jumps which go to a particular destination. Class CodeGenerator
uses vectors to store jump information and generated code.
VM Execution The VM itself is represented by a class CVM: see Figure 128. Since the language is
a concurrent language, the VM has to support an arbitrary number of processes that run indepen-
dently. Since processes are created and destroyed frequently during execution, they are stored in a
list.
11 POTPOURRI 198
class LabelEntry
{
public:
LabelEntry() : dest(0) {}
void setDestination(Address newDest) { dest = newDest; }
void addJump(Address jump) { jumps.push_back(jump); }
void setLabels(vector<Instruction> & code) const;
private:
Address dest;
list<Address> jumps;
};
class CodeGenerator
{
public:
// ....
void genConditionalJump(int line, Index ix,
Address expr, bool cond);
// ....
private:
vector<LabelEntry> entries;
vector<Instruction> code;
};
class CVM
{
public:
CVM(bool tracing, Process *program);
void unblock(int portindex);
void run();
private:
list<Process*> processes;
};
Figure 129 shows the class Process. A process has its own memory (mem) and shares a single
block of code with other processes (pointer to pcode). The Index pc (“program counter”) holds
the address of the current instruction and the enumeration status tells whether this process is
RUNNABLE, BLOCKED (waiting to communicate with another process), or FINISHED.
The heart of the VM is the function Process::step, which has a switch statement for each
kind of instruction. Figure 130 shows the code for JPT (jump if true). The function getArg
fetches the value of one of the instruction’s argument from the data memory of the process and
11 POTPOURRI 199
class Process
{
public:
Process(vector<Instruction> * pcode, Memory literals,
Address entry, Address size, Datum * port, bool main);
void step(bool tracing, list<Process*> & processes);
void checkType(int num, BasicType type);
void checkNotNull(int num);
void unblock(list<Process *> & processes, int portindex);
private:
static int procCounter;
int procNumber;
vector<Instruction> * pcode;
Memory mem;
Index pc;
StatusType status;
int portindex;
};
The VM includes extensive self-checking. The function checkType checks that the operand is
non-null and has the expected type:
The function runTimeError displays a message on the console and throws an exception to
terminate execution:
11.2 Auto-pointers
Koenig and Moo has a chapter on (almost) automatic memory management (2000, Chapter 14).
Most of the ideas in this chapter are encapsulated in a standard class auto_ptr.
void f()
{
Gizmo *pg(new Gizmo);
.... // do some stuff
delete pg;
}
1. If we forget to include the delete statement, the program has a memory leak.
2. It would actually be pretty stupid to forget to write delete, but if “do some stuff”
throws an exception, the program has a memory leak anyway.
#include <memory>
void f()
{
auto_ptr<Gizmo> pg(new Gizmo);
.... // do some stuff
} // *pg deleted here
The variable pg behaves in the same way as a pointer: we can use * or -> to dereference it, the
increment (++) and decrement (-) operators work, and so on. The difference is that the Gizmo is
automatically deleted at the end of the scope or when the stack is unwound when an exception is
thrown.
Auto-pointers have some special properties that make them different from ordinary pointers. These
properties are necessary to avoid memory problems when auto-pointers are copied or passed
around.
The basic idea is that an auto-pointer has an owner who is responsible for deleting the object
pointed to. In the simple code above, the function f is the owner and the deletion occurs when f
returns. There are more complicated situations: in the following explanations, assuming that pt
has type auto_ptr<T>.
• pt.get() returns the private variable pt.myptr which is an ordinary pointer of type T*
used by the object pt to accomplish its magic.
• pt.release() also returns myptr but then sets its value to null. The caller has taken
ownership of the auto-pointer and is now responsible for releasing it.
• The assignment operator transfers ownership from one auto-pointer to another. Specifically,
the assignment pt1 = pt2 has an effect equivalent to
delete myptr;
myptr = pt2.release();
We can use an auto-pointer to implement a safe pimpl (Sutter 2000, page 154), as shown in Fig-
ure 131. Note that the destructor C::~C has nothing to do, because the implementation object
will be destroyed by the auto-pointer. Since it is not safe to make copies of an instance of C, the
copy constructor and assignment operator are private and unimplemented.
// c.h // c.cpp
#endif
Figure 131: Auto-pointers make safe pimpls
The ownership property of auto-pointers has some interesting consequences. When the program in
Figure 132 is executed, it displays:
Woof!
Walking around the park ...
Aaargh!
Now we’re back at home
11 POTPOURRI 203
#include <memory>
#include <iostream>
class Dog
{
public:
Dog() { cout << "Woof!" << endl; }
~Dog() { cout << "Aaargh!" << endl; }
};
void main()
{
PD pd(new Dog);
walk(pd);
cout << "Now we’re back at home" << endl;
}
Note the order of events carefully. The auto-pointer pd is set pointing to a newly constructed Dog.
The auto-pointer is then passed by value to the function walk, which thereby assumes ownership
of the Dog. The Dog walks around the park until the end of the scope. When walk returns, pd no
longer points to the Dog, which expired at the end of its walk.
Warning! The ownership behaviour of auto-pointers is incompatible with the expectations of STL
containers. Declarations such as this should never be used:
For example, a sorting algorithm may select one element of a vector as a pivot and make a local
copy of it. The pivot is then used to partition the array. If the vector contains auto-pointers, copying
an element will invalidate the element! Consequently, sorting will delete the pivot and the sorted
array will contain a null pointer.
11.3 Multithreading
The first computers performed only one task at a time. After a few years of development, however,
people became concerned about the waste involved in keeping a very expensive machine idle, even
if the idle periods were only the milliseconds required to read a punched card or paper tape.
Concurrency, called multitasking, was first provided as a feature of operating systems, enabling the
processor to switch tasks when a task became “blocked”, for example, while performing input or
output. The name process was introduced to describe a task that might or might not be running at
a given time.
The theory of cooperating sequential processes was worked out by Edsger Dijkstra, Tony Hoare, and
Per Brinch Hansen. Dijkstra introduced semaphores as a low-level synchronization primitive, Hoare
and Brinch Hansen added monitors for higher-level control of synchronization.
Since that time, operating systems have provided safe multitasking, usually based on some version
of the basic operations worked out by Dijkstra, Hoare, and Brinch Hansen. Unfortunately, the same
cannot be said for languages. The early work showed that safe concurrency could be enforced
only by the compiler; it is not possible to provide safe functions in a library. The only widely-
used language that provides safe concurrent operations as part of the language is Ada.30 Other
languages, including C++, provide libraries for concurrent programming, although this practice is
known to be unsafe.
Before going further, we need some definitions. Sequential code executes in a fixed order deter-
mined by control structures. For example, s1 ; s2 ; . . . sn means “execute s1 , then execute s2 , and
so on”. A process is the execution of sequential code with interruptions. For example, “execute s1 ,
then go off and do something else for a while, execute s2 , and so on”. A process uses the processors
registers, has its own run-time stack, and uses the memory-protection facilities of the processor to
prevent code from accessing memory outside the area allocated to the process.
A thread is like a process, but does not use the processor’s memory-protection features. Typi-
cally, threads run within a process, and the process is memory-protected. Since changing memory
bounds is typically an expensive operation, and control can be transferred between threads without
changing bounds, threads are considered light-weight and processes are considered heavy-weight.
Above, we have referred to “safe” concurrency. What does this mean? What does the (incomplete)
program in Figure 133 print assuming that both threads run to completion?
If we run this program many times, we will find that it usually prints "1111" but that it sometimes
replaces one or two 1s by 0s: e.g., "1101" or "0101" but never "0100" or "0000". The
program has what is known as a race condition, and its results depend on the exact way in which
the operations of the two threads are interleaved.
The pioneers recognized that race conditions can occur only when there are variables that can be
accessed by two or more threads concurrently. Let’s call these shared variables. When a thread is
manipulating a shared variable, it must be protected from interruption by another thread. A chunk
of code that manipulates a shared variable is called a critical region. Synchronization primitives
ensure that a thread can execute its critical regions without interruption.
30
Java provides the keyword synchronized but the Java compiler does not, and cannot, check for safety. See
(Brinch Hansen 1999).
11 POTPOURRI 205
// thread 1 // thread 2
++s.c1; ++s.c3;
++s.c2; ++s.c4;
cout << s.c1 << s.c2 << s.c3 << s.c4 << endl;
Threads are not mentioned in either the C Standard nor the C++ Standard. There are, however,
thread libraries. One of the best known is Posix threads. The Posix Standard used to be in the public
domain but has now been taken over by IEEE, which means that you have to pay for the Standard.
Posix threads library components are usually declared in threads.h, which is available on many
unixTM /linux systems. In Windows, MFC provides multithreading.
The primitive operation provided by a threads library is mutual exclusion, usually abbreviated to
mutex. Mutex operations cannot be coded in a high-level language because they depend on special,
non-interruptible instructions provided by all modern processors. A typical instruction for mu-
tual exclusion is test-and-increment, which checks whether a memory location contains and also
increments it.
For object-oriented applications, it is convenient to define a class Mutex with at least two opera-
tions:
Mutex mtx;
mtx.acquire(); // Acquire a lock
mtx.release(); // Release the lock
In between calling acquire and release, a thread cannot be interrupted by another thread.
Critical regions are therefore bracketed by these operations.
Note that Mutex is not trivial to implement. A thread that fails to obtain a lock must be blocked
and placed on a queue of waiters. When a thread releases a lock and the queue is not empty, the
first thread in the queue must be activated.
11 POTPOURRI 206
class Account
{
public:
void deposit(int amount)
{
mtx.acquire();
balance += amount;
mtx.release();
}
The “Hello, world” example for concurrent programming is a bank account that can be accessed by
different threads. Figure 134 shows a simple account class. The danger with this kind of code is
that the programmer will remember to acquire the lock and forget to release it.
C++ techniques come to the rescue.31 We can define a template class Lock (Figure 135), a base
class Synchronized for objects that require synchronization (Figure 136), and a version of class
Account that uses the new facilities (Figure 137). The programmer still has to remember to lock
critical operations, but the constructor and destructor of Lock ensure that any Mutex that is
acquired is later released.
Class Account uses internal locking. There are two other possibilities, and all three are defined
below:
Internal Locking Each class ensures that concurrent calls cannot corrupt the class. The usual way
to do this is to place a lock on any access to the class’s data, as in class Account.
External Locking Classes guarantee to synchronize access to static or global data but do not pro-
tect their instance variables. Clients must lock all invocations of their member functions.
Caller-ensured Locking The class has a Mutex object (like class Synchronized) but does not
manipulate it. Instead, clients are expected to do the locking:
{
31
Actually Alexandrescu: see http://www.informit.com/articles/article.asp?p=25298&rl=1
29/11/05.
11 POTPOURRI 207
class Synchronized
{
public:
void acquireMutex() { mtx.acquire(); }
void releaseMutex() { mtx.release(); }
private:
Mutex mtx;
};
Account acc;
....
Lock<Account> guard(acc);
acc.deposit(50000);
}
Unfortunately, all three methods have disadvantages. Suppose we use internal locking for an ATM
which charges a fee of $5 for each withdrawal. Suppose further that the design requires that there
must be no transaction between withdrawing the amount and charging the fee. The code at the top
of Figure 138 does not satisfy this requirement because it might be interrupted between the two
withdrawals. The obvious correction is to apply a lock that holds over both calls, as at the bottom
of Figure 138. The revised code will work if Mutex supports recursive locking — a single thread
can lock/unlock the same object more than once. Nevertheless, it is inefficient because two levels of
locking are unnecessary. In a large application, a single object might be locked many times before
actually being used.
Another possibility is that Mutex does not support recursive locking; in this case, the code above
will deadlock when it attempts to lock the account twice.
Caller-ensured locking avoids this particular problem, but still requires discipline from clients.
Here is the design problem: the class Account consists of a finite amount of code and is therefore
bounded; the rest of the application uses Account and may be of any size — it is unbounded.
With caller-ensured and external locking, we have to examine unbounded code to be sure that
synchronization is correct. We have lost encapsulation.
Alexandrescu shows how to make better locks by exploiting C++ features. Figure 139 shows his
class Lock. The new kind of Lock must be an automatic (stack-allocated) variable and must be
associated with a particular object. Locks cannot be passed by value to functions or returned from
functions. It is possible pass Locks by reference because no copy is made. Disabling the address
operator makes it hard (but not impossible) to create aliases of a Lock. The result is that if you
own a Lock<T> then you have in fact locked a T object and that object will eventually be unlocked.
Figure 140 shows how we use the new Lock. Each function in the class has two versions. The first
version has a Lock parameter and is intended to be used with external locking: the client acquires
11 POTPOURRI 209
~Lock()
{
client.releaseMutex();
}
private:
T client;
// no default constructor
Lock();
// no copy constructor
Lock(const Lock &);
// no assignment
Lock & operator=(const Lock &);
// no address taking
Lock * operator&();
};
private:
int balance;
};
a lock and passes it by reference to the function. The second version has no Lock parameter and
implements internal locking by acquiring the lock itself. For a simple transaction, we rely on the
internal lock:
Account acc;
acc.deposit(500);
11.4 LOKI
The LOKI library was built by Andrei Alexandrescu and others and is described in Alexandrescu’s
book (2001). It shows how features of C++ can be combined in unexpected ways to give useful
results. The complete library implements policy classes, static assertions, type lists, small object
allocators, generalized functions, singletons, smart pointers, factories, and a “minimalist” multi-
threading library. Here, we describe static assertion and policy classes briefly.
The assert macro is useful, but it doesn’t do anything until run-time. It is sometimes useful
to check a condition at compile-time, causing a compile-time error if the condition is false. It is
even more useful if the compiler’s error message describes the problem. For example, the following
program does not compile:
int main()
{
StaticAssert(sizeof(char) < sizeof(int),
char_is_smaller_than_int);
StaticAssert(sizeof(int) >= 8,
int_has_at_least_eight_bytes);
}
The second argument of StaticAssert must be a valid C++ variable name but the variable does
not have to be defined. The error messages from the compiler are:
The second message tells the programmer that the assumption “ints have eight bytes” is incorrect.
LOKI defines StaticAssert in various ways for different compilers to ensure that the error
message is useful. The Windows version is quite simple:
The preprocessor converts the source code written by the programmer to this form:
int main()
{
typedef char ERROR_char_is_smaller_than_int[1]
11 POTPOURRI 212
The “[1]” in the macro definition looks unnecessary. If we omit it, however, the compiler issues
only the first error message, which is not helpful to the programmer.
11.4.2 Policies
It is easy to design simple classes for particular applications; it is much harder to design classes
that are useful for many applications. Consider a smart pointer class (Cf. Section 11.2). Should it
assume a single thread or multiple threads? How should it manage ownership — reference counting,
linking, or some other way? Should we define a whole collection of classes:
BasicSmartPointer
SingleThreadedSmartPointer
MultiThreadedSmartPointer
RefCountedSmartPointer
MultiThreadedRefCountedSmartPointer
and so on? Alexandrescu argues that this problem cannot be solved properly either by inheritance
(even with multiple inheritance) or with templates. However, we can get the effects we need by
using both templates and inheritance.
The first step is to define policy classes. These are classes that implement a particular operation in
various ways. Figure 141 shows three possible ways of allocating a new object: the first uses new,
as usual; the second uses malloc and the “placement” version of new; the third returns a clone
of a prototype ((Alexandrescu 2001, page 8)). Each class implements a single static function,
create.
Classes that perform dynamic allocation are defined as template classes that inherit a particular
policy:
The team leader then tells the grunt programmers to use instances of WidgetManager and to
call create when they want to construct a new Widget.
The STL uses policy classes for memory allocation in exactly this way. For example, the class
vector is actually defined as
11 POTPOURRI 213
Usually, we write declarations of the form vector<double>, which use the default allocator. If
we want to manage memory in a special way, however, we can define our own allocator class. This
class must provide a set of features so that it can be used correctly by the class vector. These
features are described in various places, e.g., (Musser, Derge, and Saini 2001, Chapter 24).
11.5 Boost
Boost is a set of libraries intended to help advanced C++ programmers. Some of the libraries are
candidates for inclusion in the STL. Aspects of the Boost libraries are described in (Abrahams and
Gurtovy 2005). Boost includes traits, described briefly in Section 11.5.1, but most of its libraries are
based on template metaprogramming, described in Section 11.5.2.
11.5.1 Traits
Traits provide compile-time information about types and are used in template classes. You can
determine whether a type is a simple type, a pointer type, or a reference type. As a more interesting
example, you might want to know the most efficient way of passing an argument to a function. With
a specific type, such as char or EnormousObject, this is easy. But with a template type T, it
is not so obvious. A type traits class can convert T into a type ParameterType which gives the
best way of passing Ts to functions.
The template argument corresponding to charT determines the type of character. The default is
char and the most common alternative is wchar_t, which gives Unicode.
The template argument corresponding to traits defines properties of the character type. These
properties allow the functions of basic_ostream to be written so as not to depend on the
particular character type. The class char_traits<char> contains, inter alia:
• functions to assign, compare, move, and copy chars and char arrays
11 POTPOURRI 215
The Boost library TypeTraits provides ten basic tests for type properties:
Boost also provides comparisons between types (is_same<T1,T2>, is_base<B,D>, etc.) and
type transformations (remove_const<T>, add_pointer<T>, etc.).
Here is a simplified application of these metafunctions. There is a fast way and a slow way to swap
two iterators. If the iterators are the same type and they are both reference types, we can use the
standard template function swap. In all other cases, we have to explicitly code the swap to provide
for conversions. The problem is to make this decision at compile-time.
template<>
struct iter_swap_impl<true>
{
template <class Iterator1, class Iterator2>
static void doSwap(Iterator1 i1, Iterator2 i2)
{
std::swap(i1, i2);
}
};
template<>
struct iter_swap_impl<false>
{
template <class Iterator1, class Iterator2>
static void doSwap(Iterator1 i1, Iterator2 i2)
{
typename iterator_traits<Iterator1>::value_type tmp = *i1;
*i1 = *i2;
*i2 = tmp;
}
};
The solution requires two versions of the swapping code with a bool template parameter, shown
in Figure 142, and a way of providing a template argument that is either true or false depending
on the types of the iterators, shown in Figure 143.
11 POTPOURRI 216
Template metaprogramming appeared in the C++ world in 1989. Towards the end of a workshop
on generic programming, Kristof Czarnecki and Ullrich Eisenecker showed C++ source code for a
LISP interpreter. LISP interpreters are commonplace but this one had an interesting feature: it was
executed by the compiler. For example, if you gave it (the equivalent of) a LISP expression with the
value 42, it would generate the C++ program
Although the interpreter was initially seen as a mere curiosity, interest developed rapidly, and
template metaprogramming (TM) is now viewed as an important tool in the advanced programmer’s
kit.
int main()
{
cout << binary<101010>::value << endl;
return 0;
}
This magic is accomplished by the template class shown in Figure 144. The first point to note is
that 101010 is actually a decimal number that contains only the digits 0 and 1. Given a decimal
number N, the last digit is N % 10 and the preceding digits are N / 10. To obtain the binary
value, however, we must multiply the k’th digit by 2k .
The template class Binary extracts the last digit of its template argument N and uses recursion
to get the other digits. Eventually, it will instantiate Binary<0>, and we provide a specialization
of the template class that assigns 0 to Binary::value in this case.
11 POTPOURRI 217
template<>
class Binary<0>
{
public:
static unsigned const value = 0;
};
11.5.3 MPL
The Boost library MPL provides a service similar to the class Quantity of Assignment 2 (that is,
dimensions of variables are checked statically), but it does so in a more elaborate way. For example,
instead of defining operator* as
template<int L1, int M1, int T1, int L2, int M2, int T2>
Quantity<L1+L2,M1+M2,T1+T2>
operator*(const Quantity<L1,M1,T1> & x, const Quantity<L2,M2,T2> & y)
{
return Quantity<L1+L2,M1+M2,T1+T2>(x.value() * y.value());
}
• The MPL represents dimensions using type sequences, which appear above as D1 and D2.
Thus D1 might correspond to <1,0,0>, which is a mass.
11 POTPOURRI 218
• The MPL provides template metafunctions that take dimension types as arguments and return
new dimension types. Thus transform<D1,D2,plus_f>::type is the type obtained
by adding the components of D1 and D2, and is therefore appropriate for multiplication.
The Curiously Recurring Template Pattern (CRTP) was named by James Coplien. Here it is:
The CRTP depends on the order in which the compiler does things. As an example, Figure 145
shows a class that enables us to provide operator> for any class that already has operator<.
If we have a class Widget which provides operator<, we modify its declaration to
and it provides operator> as well! After template expansion, Widget inherits operator>
from its base class
class orderedWidget
{
public:
bool operator>(const Widget & rhs) const
{
const Widget & self = static_cast<const Widget &>(*this);
return rhs < self;
}
};
11 POTPOURRI 219
This trick requires downcasting, which is not generally recommended. We can see that it is safe
enough in this application, however, because we know for certain that *this is a Widget.
11.6 Blitz++
Blitz++ (Veldhuizen 1995) was the first C++ library to make heavy use of template metaprogramming
and it had a considerable effect on the C++ community. Blitz++ provides many things, but its single
most important contribution is efficient array manipulation using expression templates. We will
briefly describe the key problem that Blitz++ solves.
m = a + b + c + d;
in which each variable is a matrix. The obvious implementation of operator+ for matrices is
likely to be something like the function in Figure 146 and the assignment above will invoke it three
times.
This is in fact pretty much what Blitz++ would generate from the original assignment. It uses
template capabilities to parse an expression and generate code that rebuilds the expression.
• The first three declarations introduce i, j, and k as index variables for the first, second, and
third dimensions of arrays.
11 POTPOURRI 220
• The Range declaration specifies that indexes should be 1,2,3,4 (instead of the usual 0,1,2,3).
1
Aij =
i+j −1
int main()
{
firstIndex i;
secondIndex j;
thirdIndex k;
Range r(1,4);
11.7 Envoi
It does seem, sometimes, as if the mentality of the best C++ programmers is very close to the
mentality of the best hackers: when you want to do something, choose the construct that looks
least appropriate and bend it into the required shape. Consider manipulators. Consider what
happens when we write:
cout << "The answer is " << setw(8) << answer << ’.’ << endl;
11 POTPOURRI 221
ManipulatorForInts setw(int n)
{
return ManipulatorForInts(ios::width, n);
}
class ManipulatorForInts
{
friend ostream & operator<<(ostream & os,
const ManipulatorForInts & m);
public:
ManipulatorForInts (int (ios::*)(int), int);
private:
int (ios::*memberfunc)(int);
int value;
}
The friend function operator« applies the member function of ManipulatorForInts to the
value supplied by the user:
Naturally, the actual implementation much more complicated than this because it is defined in the
template class basic_ostream. It seems like a lot of effort just to set the width of an output
stream.
On the positive side, C++ is still a language that is widely used, and will continue to be used, for
important applications. It will not be replaced quickly.
Alistair Cockburn: I consider C++ the most significant technical hazard to the survival of your project
and do so without apologies.
Robert Firth: C++ has its place in the history of programming languages — just as Caligula has his
place in the history of the Roman Empire.
Eric Lee Green: C++ is an atrocity, the bletcherous scab of the computing world, responsible for more
buffer overflows, more security breaches, more blue screens of death, more mysterious failures than
any other computer language in the history of the planet Earth.
11 POTPOURRI 222
Stan Kelly-Bootle: Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I
thought, proper consideration.
David Keppel: It has been discovered that C++ provides a remarkable facility for concealing the trivial
details of a program — such as where its bugs are.
Donald Knuth: Whenever the C++ language designers had two competing ideas as to how they should
solve some problem, they said, “OK, we’ll do them both”. So the language is too baroque for my taste.
Bertrand Meyer: There are only two things wrong with C++: The initial concept and the implementa-
tion.
Thant Tessman: Being really good at C++ is like being really good at using rocks to sharpen sticks.
∼
A CODING STANDARDS 223
A Coding Standards
Coding standards must be strict enough to be useful and relaxed enough that programmers actually
use them. It is unreasonable to expect all of the programmers in a large project to follow a strict
set of rules exactly. It is more realistic to provide guidelines that have enough freedom to satisfy
creative egos.
You can find a more detailed discussion of coding standards in (Sutter and Alexandrescu 2005). For
less money, you can get (Misfeldt, Bumgardner, and Gray 2004), but it’s not as good.
A.1 Rules
• Choose a layout convention and use it consistently within a file of source code.
Layout conventions are illustrated below. It doesn’t matter which one you choose; the im-
portant thing is to use it consistently. It is a good idea to use the same convention for every
source file that you create; it is essential that you stick to one convention within a file.
• Choose a naming convention and use it consistently within a file of source code.
As with layout, it is desirable to use a consistent naming convention for every file you create
and essential to stick to a convention within a file.
23/11/05
A CODING STANDARDS 224
A.2 Layout
This section and subsequent sections outline coding conventions that help you to write code that
is easy to understand for both you and other programmers. Remember that maintainers will spend
more time reading your code than you will spend writing it; try to make their lives easier.
Layout is the organization of white space in your program. It is pointless to argue about which
layout convention is “best” but it is important to organize code in a way that maximizes clarity and
minimizes potential confusion. Even experienced programmers can look at
for a minute or two without realizing that the effect of this code on array b is indeterminate.
Here are some of the more commonly used conventions for indenting compound statements and
other structures: use one for writing and be prepared to read the others.
if (store.isEmpty()) {
// do something
} else {
// do another thing
}
if (store.isEmpty())
{
// do something
}
else
{
// do another thing
}
3. Braces aligned and indented (not really any better than 2):
if (store.isEmpty())
{
// do something
}
else
{
// do another thing
}
23/11/05
A CODING STANDARDS 225
If there is one thing that can be guaranteed to mess up layout, it is the tab character. It is important
to distinguish the tab key and the tab character. The key is very useful because it allows you to
align code consistently with very little effort. The character is a disaster because users interpret it
in different ways.
To put it simply: if X writes code with a tab separation of 5 spaces, and Y revises the code with a
tab separation of 3 spaces, the result is a mess.
The solution is simple: use the tab key when entering text but never put tab characters in a file.
Figure 148 shows how to set the VC++ editor so that it does most of the layout work for you
(Indenting = Smart) but writes space characters (no tabs) to the file (Insert spaces).
A.3 Comments
Experienced programmers prefer to read and understand code without the aid of comments. They
know, from bitter experience, that the code is a more reliable guide to what the program actually
does.
23/11/05
A CODING STANDARDS 226
However, you will sometimes come up with tricky code after thinking deeply about a problem and
rejecting alternative solutions. In this case, it may help the maintenance programmer (who might
be you, six months later) by explaining why you write the code in a particular way.
The only realistic way of keeping documentation consistent with code is to write the documentation
as part of the code and then extract it using a tool such as Doxygen.32 Figure 149 shows a function
commented for Doxygen and the result as seen by a browser. Note the use of Doxygen markup such
as \b, \param, and \return. If you use a tool such as Doxygen, use it consistently: provide
documentation for all visible entities in a way that will help others to use the library, or whatever it
is, effectively.
A.4 Names
Many different kinds of names appear in C++ programs. Naming conventions make programs easier
to read and help to avoid trivial errors. The following conventions are widely used and recom-
mended.
• Names of constants are usually upper case, or start with an upper case letter. Words within a
name are separated by underscores.
• Variables and functions usually start with a lower case letter. Words within a name may be
distinguished either with upper case letters or underscores.
• Names of classes and types (other than the built-in types) usually start with an upper case
letter.
Widget ChequingAccount Name_With_Underscores
• Long names are not always better — in fact, a high proportion of long names increase the
number of lines of code and make the program harder to read. Shorter names require ab-
breviations: the important thing is to ensure that the abbreviations are unambiguous in the
context.
32
www.doxygen.org
23/11/05
A CODING STANDARDS 227
/**
* Construct a vector normal to the polygon defined
* by the given points using Martin Newell’s algorithm.
* The normal vector will be exact if the points lie in a plane,
* otherwise it will be a sort of average value. As with OpenGL,
* the vector will point in the direction from which the points
* are enumerated in a counter-clockwise direction.
*
* Unlike other functions, this function does \b not use
* homogeneous coordinates. The points are assumed to have
* (x,y,z) coordinates; the w component is ignored.
* \param points is an array of points.
* \param numPoints is the number of points in the array.
* \return the vector normal to the plane defined by \a points.
* \note The vector is \b not a unit vector because it will probably
* be averaged with other vectors.
*/
Vector(Point points[], int numPoints);
23/11/05
A CODING STANDARDS 228
• Some programmers like to distinguish data members from other variables. E.g., pos is a
simple variable and pos_ is a data member.
Hungarian Notation (HN) was introduced by Charles Simonyi33 of Microsoft. People have under-
stood HN in two different ways, leading to great confusion.
In HN, each variable has a short prefix that indicates its type. The confusion has arisen because of
the use of the word “type”, which refers not to the C++ type of the variable but rather to the function
or role of the variable. The notation is called “Hungarian” partly because Simonyi is Hungarian and
partly because the notation makes variable names unpronounceable, like Hungarian.34
The wrong way to use HN is illustrated by Microsoft’s own coding conventions in which, for exam-
ple, the prefix lpsz means “long pointer to s with zero terminator”, as in lpszWindowTitle.
This is a bad convention because the information provided by lpsz is:
• redundant. The variable declaration tells you the type of the variable.
• probably wrong. A maintenance programmer who changed the type of the variable would
almost certainly not change the name because of the risk of missing some occurrences.
• not helpful. A maintenance programmer probably knows that the variable is a string but
needs to know why it is a string.
Most of the people who claim not to like HN have misunderstood it and are using it the wrong way.
The right way to use HN is to invent prefixes that provide useful information: the prefix indicates
the “intent” rather than the “type”. In particular, variables with the same C++ type but with different
roles often have different prefixes.
The “right” way is what Simonyi originally proposed: it was his unfortunate use of the word “type”
that led to the confusion. Here is what he says (my italics):35
As suggested above, the concept of “type” in this context is determined by the set of operations
that can be applied to a quantity. The test for type equivalence is simple: could the same set of
operations be meaningfully applied to the quantities in questions? If so, the types are thought
to be the same. If there are operations that apply to a quantity in exclusion of others, the type
of the quantity is different.
The concept of “operation” is considered quite generally here; “being the subscript of array
A” or “being the second parameter of procedure Position” are operations on quantity x
33
Chief designer of a program called “Microsoft Word”.
34
If you don’t speak Hungarian, that is.
35
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs600/html/HungaNotat.
23/11/05
A CODING STANDARDS 229
(and A or Position as well). The point is that “integers” x and y are not of the same type
if Position(x,y) is legal but Position(y,x) is nonsensical. Here we can also sense
how the concepts of type and name merge: x is so named because it is an X-coordinate, and
it seems that its type is also an X-coordinate. Most programmers probably would have named
such a quantity x. In this instance, the conventions merely codify and clarify what has been
widespread programming practice.
• Positions in a table are represented by ints, but have prefixes r for row and c for column.
• In a physics application, variables could be prefixed by l, m, t, v, etc. This does not enable
the compiler to perform checks (as in Assignment 2) but it does help programmers to detect
obvious mistakes such as adding quantities with different dimensions.
Some people use “Systems Hungarian” to refer to the “wrong” way to use HN and “Apps Hungarian”
to refer to the “right” way. It is also perhaps worth noting that the popular language perl uses a
form of HN: $ prefixes scalars, @ prefixes arrays, % prefixes hashes, etc.
PI and TITLE are constants, and 3.1415926535 and "Glossary" are literals.
Use constants rather than literals whenever possible. Even when a string literal is self-describing, it
is often better to give it a name in a constant declaration.
A.6 const
• If a function does not change the value of its argument, declare the parameter as const T & x.
23/11/05
A CODING STANDARDS 230
• If a member function does not change any data members of its object, or call a non-const
function, declare the function as const.
• If you are traversing a container without changing its contents, use a const_iterator.
Sometimes, inserting const will cause a compiler error, typically of the form “cannot convert from
T to const T.” One way to remove the error is to take out a const, but this is the wrong way.
The correct way to remove the error is usually to put in a const somewhere. For example, suppose
that the compiler produces a const error for the following code:
int totalSize = 0;
for ( vector<int>::const_iterator it = store.begin();
it != store.end();
++it)
totalSize += it->getSize();
The correction is not to change const_iterator to iterator but to add const to the dec-
laration of getSize. (If getSize changes the state of the object, then you’re really in trouble!)
class Point
{
public:
double dist()
{
++uses;
return(sqrt(sqr(x) + sqr(y)));
}
....
private:
double x;
double y;
unsigned long uses;
};
The idea is that uses counts the number of times various functions of a particular object36 are
called, but is not otherwise relevant to the state of the object. In this situation, we would like to
declare dist as const, but the statement ++uses prevents us from doing so.
The solution is to declare uses to be mutable. Making a variable mutable means “the value
of this variable can be changed without changing the logical const-ness of the object”. The new
class declaration looks like this:
36
If we wanted to count how many times the function was used by all instances, we would declare uses to be
static.
23/11/05
A CODING STANDARDS 231
class Point
{
....
private:
double x;
double y;
mutable unsigned long uses;
};
A.7 Variables
Declare variables as locally as possible. The scope of a variable should not be longer than necesary.
A.8 Functions
Design functions that do one thing well. People who call your function should no exactly what to
expect and the function should fulfill their expectations. A good rule of thumb is: you should be
able to explain what a function does in one simple sentence.
In general, a function should either return a value or have an effect. (Member functions that do this
are called accessors and mutators, respectively.)
A function that has an effect and returns a value is difficult to use well. The value must be used
in some way, as the right side of an assignment, a term in an expression, or a condition in an
if or while statement. Since the functoin also has an effect, we immedaitely have expressions
and conditions with side-effects. Understanding and maintaining code is hader in the presence of
side-effects. Worse, a maintainer may not even realize that there are side-effects and introduce
errors.
A.8.1 Parameters
Choose parameter passing modes that are semantically correct and reasonably efficient. The most
common modes are: value, reference, and constant reference.
A.8.2 Operators
Increment/decrement operators: Use the prefix versions (++i and -i) rather than the postfix
versions (i++ and i-) — they are never slower and may be faster.
The only reason to use the postfix versions is when you need the old value. But even this usage is
deprecated nowadays.
23/11/05
A CODING STANDARDS 232
Overloaded operators:
• If you overload a familiar operator, programmers will expect it to work in a familiar way.
For example, suppose you provide operator+ for class T so that programmers can write:
T a = .... ;
T b = .... ;
T c = a + b;
Programmers will then expect (≡ stands for “has the same value or effect as”):
a + b ≡ b + a
a += b ≡ a = a + b
a + 0 ≡ a
0 + a ≡ a
If T is a mathematical sort of object, they might even expect operator- in both unary and
binary forms:
a - b ≡ a + (-b)
-(-a) ≡ a
a - a ≡ 0
There are a small number of exceptions to this guideline. For example, it is a common conven-
tion to use + to concatenate strings, even though concatenation is neither commutative nor
associative. In general, however, if you provide one operator, you should provide the other
operators that might reasonably be expected to go with it.
• Use free functions, rather than member functions, for overloaded binary operators.
The operator declared as
class T
{
public:
T operator+(const T & other);
....
};
23/11/05
A CODING STANDARDS 233
the statement
prints
85 85 85
A.9 Style
Figure 150 shows a ray-tracing program written in C by Anders Gavare.37 The author has carefully
avoided using any keywords and has taken a number of others teps to make this program difficult
to read. As a result, it was one of the winners of the 2004 Obfuscated C programming contest.
Gavare’s coding style is impressive in its own way, but is not a style to be imitated. Instead, you
should try to develop a clear, simple coding style.
23/11/05
A CODING STANDARDS 234
23/11/05
A CODING STANDARDS 235
J=0;K=-10;L=-7;M=1296;N=36;O=255;P=9;_=1<<15;E;S;C;D;F(b){E="1""111886:6:??AAF
"FHHMMOO55557799@@>>>BBBGGIIKK"[b]-64;C="C@=::C@@==@=:C@=:C@=:C5""31/513/5131/
"31/531/53"[b ]-64;S=b<22?9:0;D=2;}I(x,Y,X){Y?(X^=Y,X*X>x?(X^=Y):0, I (x,Y/2,
)):(E=X); }H(x){I(x, _,0);}p;q( c,x,y,z,k,l,m,a, b){F(
);x-=E*M ;y-=S*M ;z-=C*M ;b=x* x/M+ y*y/M+
*z/M-D*D *M;a=-x *k/M -y*l/M-z *m/M; p=((b=a*a/M
b)>=0?(I (b*M,_ ,0),b =E, a+(a>b ?-b:b)): -1.0);}Z;W;
(c,x,y, z,k,l, m,a){Z=! c? -1:Z;c <44?(q(c,x ,y,z,k
l,m,0,0 ),(p> 0&&c!= a&& (p<W ||Z<0) )?(W
p,Z=c): 0,o(c+ 1, x,y,z, k,l, m,a)):0 ;}Q;T
U;u;v;w ;n(e,f,g, h,i,j,d,a, b,V){o(0 ,e,f,g,h,i,j,a);d>
&&Z>=0? (e+=h*W/M,f+=i*W/M,g+=j*W/M,F(Z),u=e-E*M,v=f-S*M,w=g-C*M,b=(-2*u-2*v+w
/3,H(u*u+v*v+w*w),b/=D,b*=b,b*=200,b/=(M*M),V=Z,E!=0?(u=-u*M/E,v=-v*M/E,w=-w*M
E):0,E=(h*u+i*v+j*w)/M,h-=u*E/(M/2),i-=v*E/(M/2),j-=w*E/(M/2),n(e,f,g,h,i,j,d-
,Z,0,0),Q/=2,T/=2, U/=2,V=V<22?7: (V<30?1:(V<38?2:(V<44?4:(V==44?6:3)))
,Q+=V&1?b:0,T +=V&2?b :0,U+=V &4?b:0) :(d==P?(g+=
,j=g>0?g/8:g/ 20):0,j >0?(U= j *j/M,Q =255- 250*U/M,T=25
-150*U/M,U=255 -100 *U/M):(U =j*j /M,U<M /5?(Q=255-210*
/M,T=255-435*U /M,U=255 -720* U/M):(U -=M/5,Q=213-110*
/M,T=168-113*U / M,U=111 -85*U/M) ),d!=P?(Q/=2,T/=
,U/=2):0);Q=Q< 0?0: Q>O? O: Q;T=T<0? 0:T>O?O:T;U=U<0?0
U>O?O:U;}R;G;B ;t(x,y ,a, b){n(M*J+M *40*(A*x +a)/X/A-M*20,M*K,
*L-M*30*(A*y+b)/Y/A+M*15,0,M,0,P, -1,0,0);R+=Q ;G+=T;B +=U;++a<A?t(x,y,a
b):(++b<A?t(x,y,0,b):0);}r(x,y){R=G=B=0;t(x,y,0,0);x<X?(printf("%c%c%c",R/A/A,
/A/A,B/A/A),r(x+1,y)):0;}s(y){r(0,--y?s(y),y:y);}main(){printf("P6\n%i %i\n255
"\n",X,Y);s(Y);}
23/11/05
B GLOSSARY 236
B Glossary
« The insert operator, used to “insert” (i.e., write) objects to a stream. With integer arguments, this
operator performs a left shift.
» The extract operator, used to “extract” (i.e., read) objects from a stream. With integer arguments,
this operator performs a right shift.
Abstract base class A class in which every function is pure virtual — that is, has a declaration of
the form
Accessor A member function that returns information about an object but does not change the
object’s state. Also called inspector.
Argument A value passed to a function when the function is called. Also called “actual parame-
ter”.
Base class A class that is intended to be used as a base for other classes to inherit from. Also
called “superclass” or “parent class”.
Binary operator An operator with two parameters. Most binary operators are infix operators.
Binding Associating a name and an attribute. The attribute may be a value (e.g., the name of a
constant is bound to the value of the constant), a type (e.g., a declaration binds a type to the
name of a variable), or some other property.
Buffer A temporary space used to store data, often a string, before it is sent somewhere else, e.g.,
written to a file.
Build The result of compiling a complete system, with all translation units recompiled.
Casting An explicit conversion from one type to another. In C, T(e) is a cast that converts the
expression e to the type T. In C++, the conversion is performed by static_cast<T>(e)
if the compiler can check the validity of the conversion or dynamic_cast<T>(e) is a run-
time check is required. There is also reinterpret_cast<T>(e) which simply treats the
bits of e as if they represented a T, without any sanity checking.
Class A named collection of functions, data, and possibly other attributes. Objects are instances
of classes.
Compilation Unit The source code that is processed by one execution of the compiler. A typical
compilation unit consists of a single implementation file; the compiler will of course read
#included files as well. A complete program usually consists of several compilation units.
Compile-time The time at which the source text is processed by the compiler. E.g., a “compile-time
error” is an error detected during compilation. See static.
28/10/05
B GLOSSARY 237
Composition The process of building a subsystem in which classes contain instances of other
classes as members. Also called layering.
Constant A value that does not change. After the declaration “const int MAX = 10;”, the
value of MAX cannot change. The “10” in this declaration is also “constant” but is technically
a literal.
Constructor A special function that first allocates memory and then initializes an object. A con-
structor for class C is called C, but constructors may be overloaded.
Container An object that is used to store a collection of objects and provide various ways to access
them.
Conversion The transformation of a value of one type into a value of another type. Some conver-
sions (e.g., char to int) are performed implicitly by the compiler; others must be explicitly
requested by the programmer as casts.
Copy constructor The constructor that is used to make a copy of an object for passing or returning
by value. The copy constructor for class C has prototype C::C(const C & c).
Declaration A declaration introduces a new name into a program. E.g., “int n;” is a declara-
tion. Many declarations (including this example) are also definitions. A declaration such as
“void f()” is not a definition because the function f is defined somewhere else. A name
can be declared many times in different parts of a program.
Deep copy A copy of a pointer structure in which nodes are copied recursively. See also shallow
copy.
Default constructor A constructor that requires no arguments. There are three possible kinds of
default constructor for a class C:
• If the class does not declare any constructors, the compiler will generate a default con-
structor that allocates space for the object and does nothing else.
Definition A definition associates stored data with a name. Only one definition is allowed for each
name.
Dependency A relationship between two program components such that one requires (or depends
on) the other in order to function or compile.
28/10/05
B GLOSSARY 238
Derived Class A class that inherits from a base class. Derived classes are sometimes called “sub-
classes” or “child” classes.
Destructor A special function that performs any necessary cleaning up before deallocating the
memory for an object. A class C has at most one destructor that is named ∼C and has no
parameters.
Directive An instruction to the compiler that does not directly affect the semantics of the program.
E.g., #include <...>.
Downcast A cast from a base class type to a derived class type. Downcasting is potentially un-
safe, because the result may be a pointer or reference to an object that does not provide the
functionality expected by the compiler.
DRY stands for “don’t repeat yourself”. Every entity in a system should have a single, unambiguous
point of definition.
Dynamic A way of saying that an event occurs during execution of the program, that is, at run-
time. E.g., “dynamic binding”.
Dynamic binding Choosing which function to call at run-time. The candidate functions all have
the same name but are in different derived classes. C++ uses dynamic binding only for virtual
functions.
Expression A combination of functions, operators, and operands that can be evaluated to yield a
value. E.g., 2+2.
File A collection of data stored outside the computer, e.g., on a disk, CD, memory-stick, etc.
File scope The scope consisting of an entire source file. A name that is declared outside any braces
({...}) is “declared at (or with) file scope”.
class Widget;
it is legal to declare references and pointers to variables of type Widget. It is not legal
to declare actual instances of Widget because this would require knowing the size of a
Widget, which the forward declaration does not provide.
Friend A function or a class that is not a class member but nevertheless has access to private
members of a class.
Function A code module that can be invoked by name. Functions may accept arguments and may
return a result. E.g., sqrt is a function and sqrt(2) is a function invocation that should
√
yield 2.
28/10/05
B GLOSSARY 239
Header file A file containing declarations only that is intended to be #included in one or more
implementation files.
Hiding A function may be declared in a derived class in such a way as to prevent access to a
function in the base class, in which case it is said to hide the base class function. This
happens, for example, if the base class function is non-virtual and the functions have different
parameter lists.
Identity comparison Two objects that are “identically equal” are in fact the same object. The
actual comparison is usually performed between pointers or references so that, for example,
p1 == p2 is true if the pointers p1 and p2 point to the same object, in which case the
objects *p1 and *p2 are identical. Compare value comparison.
Implementation inheritance A derived class that calls functions defined in its base class is said to
“inherit implementation”. Compare interface inheritance.
Infix operator An operator that is written between its arguments. For example, +, as used in a+b.
Inherit When a derived class declares its base class (or classes), it is given access to the public
and protected features of that class; we say that it inherits the features.
Inspector A member function that returns information about an object but does not change the
object’s state. Also called accessor.
Instantiate Create a particular entity from a general pattern. E.g., we instantiate a class to obtain
an object.
Interface inheritance A derived class that inherits function declarations but not their implementa-
tions is said to “inherit and interface”.
Iterator An object that is intended to process the elements of a container in a particular order.
Layering The process of building a subsystem in which classes contain instances of other classes
as members. Also called composition.
Library A collection of functions that form a coherent group. E.g., a linear algebra library.
Link-time The time at which source text is processed by the linker. The distinction between
compile-time and link-time is important mainly for classifying errors: errors within a transla-
tion unit are detected at compile-time but inconsistencies between translation units may not
be detected until link-time.
Liskov Substitution Principle “Subclasses must be usable through the base class interface without
the need for the user to know the difference.”
Literal A constant that has an immediate value (i.e., is not a name). E.g., 42, 3.14159, ’x’,
"C++".
28/10/05
B GLOSSARY 240
Lvalue An expression that may be used on the left side of an assignment operator. Technically, an
lvalue is a place where something can be stored, i.e., an address. E.g., x, a[i]. See rvalue.
Main program The unique function called main that must appear in any C++ program that can run
by itself (as opposed to a library).
Mangling When a function name is overloaded, there will be several functions with the same name.
C++ generates unique names for the linker, a process informally referred to as name mangling.
Member A data item or a function that is introduced within a class declaration. In a C++ context, we
usually refer to “data members” and “member functions”. In a general object-oriented pro-
gramming context, data members are called “instance variables” or “attributes”, and member
functions are called “methods”. The term “feature” is sometimes used to mean data or func-
tion.
Mutator A member function that changes the state of the object but (usually) does not return a
value.
Object An area of memory that stores data in a format defined by the class of which this object is
an instance.
Operator A function that has special syntax. In C++, k+2 is simply an abbreviation for operator+(k,2),
showing that + is actually a function whose full name is operator+.
Overload A single function name may be used to represent more than one actual function, pro-
vided that the functions have different parameter types. Such a name is overloaded. Infor-
mally, people refer to an “overloaded function” but, strictly speaking, it is the name that is
overloaded, not the function.
Override If a base class provides a virtual function f and a derived class provides another defini-
tion of the same function with the same parameters, the second definition is said to override
or redefine the first definition.
Parameter A formal name in a function declaration or definition. E.g., in double sqrt(double x),
“double x” is a parameter. Parameters are sometimes called “formal parameters” or even
“formal arguments”.
Polymorphism A name that may refer to different objects (literally, “have many shapes”). C++ has
three main kinds of polymorphism: overloading, dynamic binding, and templates.
Private A member of a class that can be accessed only by instances of the class.
Protected A member of a class that can be accessed only by instances of the class and its derived
classes.
Public A member of a class that can be accessed by anyone via an instance of the class.
28/10/05
B GLOSSARY 241
Pure virtual A virtual function without an implementation is called a pure virtual function. The
definition of a pure virtual function has the special form
Qualifier A class, type, or namespace name used to indicate the scope that the compiler should
use to find a name. In std::endl, std is a qualifier indicating that the compiler should
look for endl in namespace std.
Redefine If a base class provides a virtual function f and a derived class provides another defini-
tion of the same function with the same parameters, the second definition is said to redefine
or override the first definition.
Return type The type of value returned by a function. It is usually the first component of a
function definition or declaration. E.g., the return type of double sqrt(double x)
is double.
Run-time The time at which the program is executed. E.g., memory management errors are usually
not detected until run-time.
Rvalue An expression that can be used only on the right of an assignment operator. In practice,
this means expressions that cannot represent a storage location. E.g., 99, delta + 0.001.
See lvalue.
Scope A textual region of a program. An entire source file forms a scope called file scope. Other
scopes are enclosed in braces: { .... }.
Scoping operator This is the technical name of the symbol “::” used between a qualifier and a
name.
Shallow copy A copy of a pointer structure that copies the root node only. Pointers in the copied
root node point to the subrees of the root of the original tree.
Slicing Suppose that d is the name of an instance of a derived class D and b is a variable declared
as an instance of the base class, B, of D. After the assignment b = d, b has B data only, its
D parts have been sliced off.
Standard library The library that contains all of the commonly used functions of C++; or everything
in the namespace std.
Standard template library The library that contains a collection of useful data structures and al-
gorithms. Usually referred to as “STL”.
Standard stream A stream that is defined in the standard library. The most-used standard streams
are:
28/10/05
B GLOSSARY 242
Statement A unit of code that performs an action. A simple statement ends with a semicolon (“;”).
A compound statement is delimited by braces ({ .... }).
Static A way of saying that an event occurs at compile-time or link-time, i.e., before the program is
executed. E.g., type checking in C++ is static.
Stream An object used to transfer data from one place to another. The word “stream” suggests
data “flowing” from a source to a sink.
Stream library The library that contains all of the stream classes and other information that are
commonly used by C++ programs. The library is actually split into several parts: iostream,
iomanip, etc.
String A sequence of characters. A string literal is written using quotes. E.g., "Hello, world!".
String stream A stream that reads from or writes to a memory buffer. An input string streams
(istringstream) reads from a buffer and an output string stream (ostringstream)
writes to a buffer.
Translation unit A collection of files seen by the compiler as a single unit. A translation unit
typically consists of an implementation file and several header files.
Type A category that assigns an interpretation to a bunch of bits. E.g., we can understand the
meaning of a 32-bit word if we know that it is an int or a char[4].
Type checking The process of ensuring that the type declarations in the program are consistent
and cannot cause meaningless computation. Type checking is performed mostly by the com-
piler but very occasionally by the run-time system.
Upcast A cast from a derived class type “up” the class hierarchy to a base class type. Upcasting
is always safe, in the sense that nothing is left undefined, but it usually results in a loss of
information.
Value comparison A comparison in which the values of objects, rather than their names or ad-
dresses, are compared. Value comparison is weaker than identity comparison because two
objects may be value-equal (technically: extensionally equal) but be distinct objects.
Virtual function A function declared in a base class that can be redefined in derived classes to give
run-time polymorphic behaviour (dynamic binding).
YAGNI stands for “you aren’t going to need it”. It is an exhortation write only the code that you
actually need now, not the code that you might need tomorrow, next week, or . . . . never.
28/10/05
REFERENCES 243
References
Abrahams, D. and A. Gurtovy (2005). C++ Template Metaprogramming: Concepts, Tools, and Tech-
niques from Boost and Beyond. Addison-Wesley.
Alexandrescu, A. (2001). Modern C++ Design: Generic Programming and Generic Patterns Applied.
Addison-Wesley.
Austern, M. H. (1999). Generic Programming and the STL: Using and Extending the C++ Standard
Template Library. Professional Computing Series. Addison-Wesley.
Beck, K. and W. Cunningham (1989, October). A laboratory for teaching object-oriented thinking.
In Object-Oriented Programming: Systems, Languages and Applications, pp. 1–6.
Bentley, J. (1986). Programming Pearls. Addison-Wesley.
Bentley, J. (1988). More Programming Pearls. Addison-Wesley.
Brinch Hansen, P. (1999, April). Java’s insecure parallelism. SIGPLAN Notices 34(4), 38–45.
De Lillo, N. J. (2002). Object-Oriented Design in C++: Using the Standard Template Library.
Addison-Wesley.
Dewhurst, S. C. (2003). C++ Gotchas: Avoiding Common Problems in Coding and Design. Addison-
Wesley.
Dijkstra, E. W. (1976). A Discipline of Programming. Prentice-Hall.
Gamma, E., R. Helm, R. Johnson, and J. Vlissides (1995). Design Patterns: Elements of Reusable
Object-Oriented Software. Addison-Wesley.
Graff, M. G. and K. R. van Wyk (2003). Secure Coding: Principles and Practices. O’Reilly.
Hoare, C. (1981, February). The emperor’s old clothes. Communications of the ACM 24(2), 75–83.
Reprinted in (Hoare and Jones 1989).
Hoare, C. and C. Jones (1989). Essays in Computing Science. Prentice-Hall.
Hoglund, G. and G. McGraw (2004). Exploiting Softweare: how to break code. Addison-Wesley.
Hunt, A. and D. Thomas (2000). The Pragmatic Programmer. Addison-Wesley.
Kernighan, B. W. and D. M. Ritchie (1978). The C Programming Language. Prentic-Hall.
Koenig, A. and B. E. Moo (2000). Accelerated C++: Practical Programming by Example. Addison-
Wesley.
Lakos, J. (1996). Large-Scale C++ Software Design. Professional Computing Series. Addison-Wesley.
Langer, A. and K. Kreft (1999). Standard C++ IOStreams and Locales: Advanced Programmer’s
Guide and Reference. Addison-Wesley.
Meyer, B. (1997). Object-Oriented Software Construction (second ed.). Professional Technical Ref-
erence. Prentice Hall.
Meyers, S. (1992). Effective C++: 50 Specific Ways to Improve Your Programs and Designs. Addison-
Wesley.
Meyers, S. (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template
Library. Addison-Wesley.
Misfeldt, T., G. Bumgardner, and A. Gray (2004). The Elements of C++ Style. Cambridge University
Press.
28/10/05
REFERENCES 244
Musser, D. R., G. J. Derge, and A. Saini (2001). STL Tutorial and Reference Guide. Professional
Computing Series. Addison-Wesley.
Parnas, D. L. (1978). Designing software for ease of extension and contraction. In ICSE ’78: Pro-
ceedings of the 3rd International Conference on Software engineering, Piscataway, NJ, USA, pp.
264–277. IEEE Press. Reprinted as (Parnas 1979).
Parnas, D. L. (1979, March). Designing software for ease of extension and contraction. IEEE Trans-
actions on Software Engineering, 128–138.
Raymond, E. S. (2004). The Art of UNIX Programming. Addison-Wesley.
Stroustrup, B. (1994). The Design and Evolution of C++. Addison-Wesley.
Stroustrup, B. (1997). The C++ Programming Language. Addison-Wesley.
Sutter, H. (2000). Exceptional C++: 47 Engineering puzzles, Programming Problems, and Solutions.
C++ In-Depth Series. Addison-Wesley.
Sutter, H. (2002). More Exceptional C++: 40 New Engineering puzzles, Programming Problems, and
Solutions. C++ In-Depth Series. Addison-Wesley.
Sutter, H. (2005). Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems, and
Solutions. C++ In-Depth Series. Addison-Wesley.
Sutter, H. and A. Alexandrescu (2005). C++ Coding Standards: 101 Rules, Guidelines, and Best
Practices. C++ In-Depth Series. Addison-Wesley.
Vandervoorde, D. and N. M. Josuttis (2003). C++ Templates: the Complete Guide. Addison-Wesley.
Veldhuizen, T. (1995, May). Using C++ template metaprograms. C++ Report 7(4), 36–43.
28/10/05