Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Starting Out with C++: Early Objects 9th

Edition by Tony Gaddis (eBook PDF)


Visit to download the full and correct content document:
https://ebooksecure.com/download/starting-out-with-c-early-objects-9th-edition-by-ton
y-gaddis-ebook-pdf/
start·ng out wi h >>>

EARLY OBJECTS
T DIT ON
"

Preface xv

Chapter 1 Introduction to Computers and Programming 1


Chapter 2 Introduction to C++ 27
Chapter 3 Expressions and Interactivity 77
Chapter 4 Making Decisions 155
Chapter 5 Looping 243
Chapter 6 Functions 323
Chapter 7 Introduction to Classes and Objects 407
Chapter 8 Arrays 507
Chapter 9 Searching, Sorting , and Algorithm Analysis 603
Chapter 10 Pointers 645
Chapter 11 More about Classes and Object -Oriented Programming 703
Chapter 12 More on ( -Strings and the string Class 815
Chapter 13 Advanced File and 1/ 0 Operations 853
Chapter 14 Recursion 915
Chapter 15 Polymorphism and Virtual Functions 949
Chapter 16 Exceptions, Templates, and the Standard Template Library (STL) 987
Chapter 17 Linked Lists 103 7
Chapter 18 Stacks and Queues 1085
Chapter 19 Binary Trees 1125

Appendix A: The ASCII Character Set 1155


Appendix B: Operator Precedence and Associativity 1159
Appendix C: Answers to Checkpoints 1161
Appendix D: Answers to Odd -Numbered Review Questions 1201
Index 1221

V
This page intentionally left blank
Preface xv

CHAPTER 1 Introduction to Computers and Programming 1

1.1 Why Program? 1


1.2 Computer Systems: Hardware and Software 3
1.3 Programs and Programming Languages 8
1.4 What Is a Program Made of? 13
1.5 Input, Processing, and Output 17
1.6 The Programming Process 18
1.7 Tying It All Together: Hi! It 's Me 23

CHAPTER 2 Introduction to C++ 27

2.1 The Parts of a C++ Program 2 7


2.2 The cout Object 31
2.3 The# i ncludeDirect ive 36
2.4 Variables and the Assignment Statement 37
2.5 Literals 39
2.6 Identifiers 41
2.7 Integer Data Types 43
2.8 Floating-Point Data Types 48
2.9 The char Data Type 52
2.10 TheC++str i ngClass 56
2.11 The bool Data Type 57
2.12 Determining the Size of a Data Type 58
2.13 More on Variable Assignments and Initialization 59
2.14 Scope 61
2.15 Arithmetic Operators 62
2.16 Comments 66
2.17 Programming Style 67
2.18 Tying It All Together: Smile! 69
vii
v iii Contents

CHAPTER 3 Expressions and Interactivity 77


3 .1 ThecinObject 77
3 .2 Mathematical Expressions 84
3 .3 Data Type Conversion and Type Casting 92
3.4 Overflow and Underflow 98
3 .5 Named Constants 99
3 .6 Multiple and Combined Assignment 102
3 .7 Formatting Output 106
3 .8 Working with Characters and Strings 116
3 .9 More Mathematical Library Functions 130
3 .10 Random Numbers 132
3 .11 Focus on Debugging: Hand Tracing a Program 136
3 .12 Green Fields Landscaping Case Study- Part 1 138
3 .13 Tying It All Together: Word Game 141

CHAPTER 4 Making Decisions 155

4.1 Relational Operators 155


4.2 The if Statement 161
4.3 Theif/elseStatement 170
4.4 The if /else if Statement 175
4.5 Menu-Driven Programs 183
4.6 Nested i f Statements 185
4.7 Logical Operators 189
4.8 Validating User Input 198
4.9 More about Blocks and Scope 200
4.10 More about Characters and Strings 203
4.11 The Conditional Operator 209
4.12 The switch Statement 213
4.13 Enumerated Data Types 222
4.14 Focus on Testing and Debugging: Validating Output Results 225
4.15 Green Fields Landscaping Case Study- Part 2 227
4.16 Tying It All Together: Fortune Teller 232

CHAPTER 5 Looping 243

5 .1 Introduction to Loops: The whi le Loop 243


5 .2 Using the while Loop for Input Validation 250
5.3 The Increment and Decrement Operators 253
5.4 Counters 258
5 .5 Keeping a Running Total 260
5 .6 Sentinels 263
5 .7 The do-while Loop 265
Contents ix

5 .8 The for Loop 271


5 .9 Focus on Software Engineering: Deciding Which Loop to Use 277
5 .10 Nested Loops 279
5 .11 Breaking Out of a Loop 281
5 .12 Using Files for Data Storage 285
5 .13 Focus on Testing and Debugging: Creating Good Test Data 301
5 .14 Central Mountain Credit Union Case Study 304
5 .15 Tying It All Together: What a Colorful World 308

CHAPTER 6 Function s 323

6.1 Modular Programming 323


6.2 Defining and Calling Functions 324
6.3 Function Prototypes 332
6.4 Sending Data into a Function 333
6.5 Passing Data by Value 338
6.6 The return Statement 342
6.7 Returning a Value from a Function 343
6.8 Returning a Boolean Value 349
6.9 Using Functions in a Menu-Driven Program 351
6.10 Local and Global Variables 355
6.11 Static Local Variables 362
6.12 Default Arguments 364
6.13 Using Reference Variables as Parameters 368
6.14 Overloading Functions 378
6.15 The exit() Function 382
6.16 Stubs and Drivers 385
6.17 LittleLottoCaseStudy 387
6.18 Tying It All Together: Glowing Jack-o-lantern 392

CHAPTER 7 Introduction to Classes and Objects 407

7.1 Abstract Data Types 407


7.2 Object-Oriented Programming 409
7.3 Introduction to Classes 411
7.4 Creating and Using Objects 414
7.5 Defining Member Functions 416
7.6 Constructors 423
7.7 Destructors 429
7.8 Private Member Functions 432
7.9 Passing Objects to Functions 435
7.10 Object Composition 442
7.11 Focus on Software Engineering: Separating Class Specification, Implementation ,
and Client Code 446
x Contents

7.12 Structures 453


7.13 More about Enumerated Data Types 465
7.14 Home Software Company OOP Case Study 469
7.15 Introduction to Object-Oriented Analysis and
Design 476
7.16 Screen Contro l 486
7.17 Tying It All Together: Yoyo Animation 491

CHAPTER 8 Arrays 507

8.1 Arrays H old Multiple Values 507


8.2 Accessing Array Elements 509
8.3 Inputting and Displaying Array Data 511
8.4 Array Initialization 518
8.5 The Range-Based for loop 525
8.6 Processing Array Contents 528
8.7 Using Parallel Arrays 539
8.8 The typede f Statement 543
8.9 Arrays as Function Arguments 543
8.10 Two-Dimensional Arrays 553
8.11 Arrays with Three or More Dimensions 560
8.12 Vectors 563
8.13 Arrays of Objects 575
8.14 National Commerce Bank Case Study 585
8.15 Tying It All Together: Rock, Paper, Scissors 587

CHAPTER 9 Searching, Sorting , and Algorithm Analysis 603

9 .1 Introduction to Search Algorithms 603


9.2 Searching an Array of Objects 610
9.3 Introduction to Sorting Algorithms 613
9.4 Sorting an Array of Objects 621
9.5 Sorting and Searching Vectors 624
9.6 Introduction to Analysis of Algorithms 627
9.7 Case Studies 635
9.8 Tying It All Together: Secret Messages 635

CHAPTER 10 Pointers 645


10.1 Pointers and the Address Operator 645
10.2 Pointer Variables 647
10.3 The Relationship Between Arrays and
Pointers 651
Contents xi

10.4 Pointer Arithmetic 655


10.5 Initializing Pointers 656
10.6 Comparing Pointers 659
10. 7 Pointers as Funct ion Parameters 661
10.8 Pointers to Constants and Constant Pointers 665
10.9 Focus on Software Engineering: Dynamic Memory
Allocation 670
10.10 Focus on Software Engineering: Returning Pointers from
Functions 674
10.11 Pointers to Class Objects and Structures 680
10.12 Focus on Software Engineering: Selecting Members
of Objects 684
10.13 Smart Pointers 686
10.14 Tying It All Together: Pardon Me, Do You Have the Time? 694

CHAPTER 11 More about Classes and Object -Oriented Programming 703

11.1 The th is Pointer and Constant Member Functions 703


11.2 Static Members 708
11.3 Friends of Classes 715
11.4 Memberwise Assignment 720
11.5 Copy Constructors 721
11.6 Operator Overloading 730
11.7 Rvalue References and Move Operations 751
11.8 Function Objects and Lambda Expressions 761
11.9 Type Conversion Operators 770
11.10 Convert Constructors 773
11.11 Aggregation and Composition 776
11.12 Inheritance 782
11.13 Protected Members and Class Access 787
11.14 Constructors, Destructors, and Inheritance 792
11.15 Overr iding Base Class Functions 797
11.16 Tying It All Together: Putting Data on the World Wide Web 800

CHAPTER 12 More on C-Strings and the s t ring Class 815

12.1 C-Strings 815


12.2 Library Functions for Working with C-Strings 820
12.3 Conversions Between Numbers and Strings 829
12.4 Writing Your Own C-String Handling Functions 833
12.5 More about the C++ str i ng Class 839
12.6 Advanced Software Enterprises Case Study 842
12.7 Tying It All Together: Program Execution Environments 844
xii Contents

CHAPTER13 Advanced File and 1/ 0 Operations 853

13.1 Input and Output Streams 853


13.2 More Detailed Error Testing 861
13.3 Member Functions for Reading and Writing Files 865
13.4 Binary Files 877
13.5 Creating Records with Structures 881
13.6 Random -Access Files 886
13. 7 Opening a File for Both Input and Output 893
13.8 Online Friendship Connections Case Study: Object Serialization 898
13.9 Tying It All Together : File Merging and Color-Coded HTML 903

CHAPTER14 Recursion 915

14.1 Intr oduct ion to Recursion 915


14.2 The Recursive Factorial Function 922
14.3 The Recursive gcd Function 924
14.4 Solving Recursively Defined Problems 925
14.5 A Recursive Binary Search Function 927
14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm 929
14.7 The Towersof Hano i 933
14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms 936
14.9 Focus on Software Engineering: Recursion versus Iteration 940
14.10 Tying It All Together : Infix and Prefix Expressions 941

CHAPTER15 Polymorphism and Virtual Functions 949


15.1 Type Compatibi lity in Inheritance Hierarchies 949
15.2 Polymorp hism and Virtual Member Functions 955
15.3 Abstract Base Classes and Pure Virtual Functions 963
15.4 Focus on Object -Oriented Programming : Composition versus Inheritance 969
15.5 Secure Encryption Systems, Inc., Case Study 973
15.6 Tying It All Together : Let's Move It 976

CHAPTER16 Exceptions, Templates, and the Standard Template Library


(STL) 987
16 .1 Exceptions 987
16.2 Function Templates 999
16.3 Class Templates 1007
16.4 Class Templates and Inheritance 1012
16.5 Intr oduct ion to the Standard Templat e Library 1016
16.6 Tying It All Together : Word Transformers Game 1029
Contents x iii

CHAPTER 17 Linked Lists 1037

17.1 Introduction to the Linked List ADT 1037


17.2 Linked List Operations 1043
17.3 A Linked List Template 1055
17.4 Recursive Linked List Operations 1059
17.5 Variations of the Linked List 1067
17.6 The STL list Container 1068
17. 7 Reliable Software Systems, Inc., Case Study 1071
17.8 Tying It All Together: More on Graphics and Animation 1074

CHAPTER 18 Stacks and Queues 1085

18.1 Introduction to the Stack ADT 1085


18.2 Dynamic Stacks 1093
18.3 The STL stack Container 1097
18.4 Introduction to the Queue ADT 1099
18.5 Dynamic Queues 1106
18.6 The STL deque and queue Containers 1109
18.7 Focus on Problem Solving and Program Design: Eliminating Recursion 1112
18.8 Tying It All Together: Converting Postfix Expressions to Infix 1117

CHAPTER 19 Binary Trees 1125

19.1 Definition and Applications of Binary Trees 1125


19.2 Binary Search Tree Operations 1129
19.3 Template Considerations for Binary Search Trees 1145
19.4 Tying It All Together: Genealogy Trees 1145

Appendix A: The ASCII Character Set 1155


Appendix B: Operator Precedence and Associativity 1159
Appendix C: Answers to Checkpoints 1161
Appendix D: Answers to Odd -Numbered Review Questions 1201
Index 1221
xi v Contents

Additional Appendices
The following append ices are located on the book's compan ion web site.

Appendix E: A Brief Introduction to Object -Oriented Programming


Appendix F: Using UMLin Class Design
Appendix G: Multi-Source File Programs
Appendix H: Multiple and Virtual Inheritance
Appendix I: Header File and Library Function Reference
Appendix J: Namespaces
Appendix K: C++ Casts and Run-Time Type Identification
Appendix L: Passing Command Line Arguments
Appendix M: Binary Numbers and Bitwise Operations
Appendix N: Introduction to Flowcharting
Welcome to Starting Out with C++:Early Objects, 9th Edition . This book is intended
for use in a two -term or three -term C++ programming sequence, or an accelerated
one-term course. Students new to programming, as well as those with prior course work
in other languages, will find this text beneficial. The fundamentals of programming
are covered for the novice, while the details, pitfalls, and nuances of the C++ language
are explored in-depth for both the beginner and more exper ienced student . T he book
is written with clear, easy-to -understand language and it covers all the necessary
topics for an introductory programming course. T his text is rich in example programs
that are concise, practica l, and real world oriented, ensuring that the student not only
learns how to implement the features and constructs of C++, but why and when to
use them.

What's New in the Ninth Edition


The New C++ 11 Standard
C++11 is the latest standard version of the C++ language . In previous years, while the
standard was being developed, it was known as C++Ox. In August 2011, it was
approved by the International Standards Organization (ISO), and the name of the
standard was officially changed to C++l l. Most of the popular C++ compilers now
support this standard.
T he new C++ 11 standard was the primary motivat ion behind this edition, which
introduces many of the new language features. H owever, a C++11 compi ler is not
strictly required to use the book . As you progress through the book, you will see
C++ll icons in the marg ins, next to the new features that are introduced . Programs
appearing in sections that are not marked with this icon will still compi le using an
older compiler.

The C++ 11 Topics Introduced in This Edition


• The aut o key word is introduced in Chapter 2 as a way to simplify comp lex
variable definitions . This key word causes the comp iler to infer a variable's data
type from its initializat ion value.

xv
xvi Preface

• Chapter 2 also introduces the new long long i nt and unsigned long long i nt
data types and the LL literal suffix.
• Chapter 5 shows how to pass a str i ng object directly to a file stream object's
open member function, without the need to call the c_s t r () member function.
A discussion of the c_s t r () function sti ll exists for anyone using a legacy
compiler.
• Th e range -based for loop is introduced in Chapter 7 . Thi s new looping
mechanism automatically iterates over each element of an array, vector, or
other collect ion, without the need for a counter variable or a subscr ipt.
• Chapter 7 also introduces strongly typed enums.
• Chapter 8 introduces new ways to initialize variables and shows how a vec t or
can now be initialized with an initia lization list.
• Chapter 10 introduces smart pointers and provides examples of how and why to use
the new uni que_ptr and shared_ptr pointers for safely allocating and working
with dynamic memory .
• Chapter 10 also introduces the move assignment operator, and the null pt r key
word, which is now the standard way of representing a null pointer.
• Chapter 11 discusses move constructors, provides more in depth coverage of
move assignment operators, and introduces lambda expressions .
• Chapter 12 introduces new functions in the C++ 11 string library and discusses
the new overloaded to _stri ng functions for convert ing numeric values to stri ng
ob jects.
• Chapter 15 introduces and demonstrates the use of the new override key word
that helps prevent subtl e over ridin g errors and the new final key word that
prevents a virtua l member function from being overridden .
• Chapter 16 introduces the new C++ 11 functions begi n ( c) and end ( c) to specify
positions within a collection c where an operat ion shou ld begin and end.

What Else is New


This book's pedagogy and clear writing style remain the same as in the previous edition.
However, in addition to upd at ing the book to introduce the new C++l 1 standard,
many improvements have been made to make it even more student -friendly.
• Upd ated Material
Material has been upd ated throughout the book to reflect changes in technology
and in software development environments, as well as to improve clarity and
incorporate best practices in teaching introductory programming . As a resu lt,
new graphics and new or redesigned figures have been added throughout the
book where appropriate and new or impr oved sample programs have been
included in a number of chapters .
• New Material
New materia l has been added on a number of topics. In add ition to introducing
and using new C++ 11 features, this new edition includes new sections on literals,
random numbers, and enumerated data types, as well as improved materia l on
designing classes.
Preface xvii

• New Programming Challenges


New Programming Challenge problems have been added to every chapter.
• Reorganized Chapters
Several chapters have been redesigned to improve student learning . Chapter 5
(Looping) has been reorganized to give st udents more practice using the whi le
loop before introducing do-while and for loops. The Chapter 6 (Fun ctions)
material on defining and calling functions has been reorganized to introduce
function prototypes earl ier and allow main to always be the first function in
a client program .

Organization of the Text


Thi s text teaches C++ in a step -by-step fashion. Each chapte r covers a major set of
topics and builds knowledge as the student progresses through the book . Although
the chapters can be easily taught in their existing sequence, flexibility is provided .
The following dependency diagram (Figur e P-1) suggests possible sequences of
instruct ion .
Chapter 1 covers fundamental hardware, software, and programm ing concepts. The
instructor may choose to skip this chapter if the class has already mastered those topics.
Chapters 2 through 6 cover basic C++ syntax, data types, expressions, selection
str uctures, repetition str uctures, and functions . Each of these chapters builds on the
previous chapter and should be covered in the order presented.
Chapter 7 introduces object -oriented programming . It can be covered any time after
Chapter 6, but before Chapter 11. Instructors who prefer to introduce arrays before
classes can cover Chapter 8 before Chapter 7 . In this case it is only necessary to
postpone Section 8.13 (Arrays of Objects) until Chapter 7 has been covered.
As Figure P-1 illustrates, in the second half of the book Chapters 11, 12, 13, and 14
can be covered in any order. Chapters 11, 15, and 16, however, shou ld be done in
sequence. Instructors who wish to introduce data structures at an earlier point in the
course, without having first covered advanced C++ and OO P features, can cover
Chapter 17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and
Binary Tr ees), any time after Chapter 14 (Recursion). In this case it is necessary to
simply omit the sections in Chapters 17- 19 that deal with templates and the Standard
Template Library.
xviii Preface

Figure P-1

Chapter1
Introduction

..
Chapters2-6
Basic
Language
Elements

• •
I

Chapter7 Chapter8
OOP Introduction Arrays
I

+
Chapter9
+
Chapter10
Searching, Sorting,
Pointers
and AlgorithmAnalysis
I

• •
I

+ Chapter12
+
Chapter13
Chapter11 Chapter14
Advanced AdvancedFiles
MoreOOP Recursion
Strings and 1/0


Chapter15
Adv.OOP

Chapter17
LinkedLists


Chapter16
Exceptions,
Templates ,
+
Chapter18
Stacksand
I

+
Chapter19
BinaryTrees
and STL Queues
Preface xix

Brief Overview of Each Chapter


Chapter 1: Introduction to Computers and Programming
T his chapter prov ides an introduction to the field of computer science and covers
the fundamentals of hardware , software, operating systems, programming, problem
so lving, and software engineering . The components of programs, such as key words,
variables, operators, and punctuation are covered . The tools of the trade , such as
hierarchy charts and pseudocode, are also presented . T he Tying It All T ogether
sect ion shows students how to use the cout statement to create a personalized
output message. Programm ing Challenges at the end of the chapter help students see
how the same basic input, processing , and output structure can be used to create
multiple programs .

Chapter 2: Introduction to C++


This chapter gets the student started in C++ by introducing the basic parts of a
C++ program , data types, the use of variables and literals, assignment statements,
simple arithmetic operations, program output, and comments . T he C++ s t ring
class is presented and string objects are used from this point on in the book as
the primary method of handling strings. Programm ing sty le conventions are
introduced , and good programming style is modeled here, as it is throughout the
text . The Tying It All T oget her section lets the student play with simple text -
based graphics.

Chapter 3: Expressions and Interactivity


In this chapter the student learns to write programs that input and hand le numer ic,
character, and string data. The use of arithmet ic operators and the creation of
mathemat ica l expressions are covered, with emphasis on operator precedence .
Debugging is introduced, with a section on hand tracing a program . Sections are also
included on using random numbers , on simp le output formatting, on data type
conversion and type casting, and on using library functions that work with numbers.
The Tying It All T ogether section shows students how to create a simple interactive
word game.

Chapter 4: Making Decisions


Here the student learns about relationa l expressions and how to control the flow of a
program with if, if I else , and if I else i f statements . Logical operators, the
cond itional operator, and the swi tch statement are also covered . Applications of these
constructs, such as menu -driven programs , are illustrated . This chapter also introduces
the concepts of blocks and scope and continues the theme of debugging with a section
on validating output results. The Tying It All T ogether section uses random numbers
and branching statements to create a fortune telling game.
xx Preface

Chapter 5: Looping
This chapter introduces, C++'s repetitive control mechanisms . The while loop, do-while
loop, and for loop are presented, along with a variety of methods to control them . These
include using counters, user input, end sentinels, and end-of-file testing. Applications
utilizing loops, such as keeping a running total and performing data validation, are also
covered . The chapte r includes an extensive section on working with files and a section
on creating good test data, continuing the book's emphasis on testing and debugging.
The Tying It All Together section introduces students to Windows commands to create
colorful output and uses a loop to create a multi-colored display .

Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both
void and value-returning functions. Parameter passing is covered, with emphasis on
when arguments shou ld be passed by value versus when they need to be passed by
reference. Scope of variables is covered and sections are provided on local versus globa l
variables and on static local variables . Overloaded functions are also introduced and
demonstrated . The Tying It All Together section includes a modular, menu -driven
program that emphasizes the versatility of functions, illustrating how their behavior
can be controlled by the arguments sent to them .

Chapter 7: Introduction to Classes and Objects


In this chapter the text begins to focus on the object-oriented paradigm . Students have used
provided C++ classes since the beginning of the text, but now they learn how to define their
own classes and to create and use objects of these classes. Careful attention is paid to
illustrating which functions belong in a class versus which functions belong in a client
program that uses the class. Good object-oriented practices are discussed and modeled, such
as protecting member data through carefully constructed accessor and mutator functions
and hiding class implementation details from client programs. Once students are comfortable
working with classes and objects, the chapter provides a brief introduction to the topic of
object-oriented analysis and design. The chapter also includes a section on enumerated data
types and a section on structures, which are used in the Tying It All Together section, where
students learn to use screen control techniques to create a yoyo animation .

Chapter 8: Arrays
In this chapter the student learns to create and work with single and multidimensional
arrays. Many examples of array processing are provided, including functions to compute
the sum, average, highest and lowest values in an array . Students also learn to create tables
using two -dimensional arrays, and to analyze array data by row or by column . Programming
techniques using parallel arrays are also demonsrrated, and the student is shown how to
use a data file as an input source to populate an array . The range -based for loop is
introduced as an easy way to iterate through all the elements of an array, and STL vectors
are introduced and compared to arrays. A section on arrays of objects and structures is
located at the end of the chapter, so it can be covered now or saved for later if the instructor
wishes to cover this chapter before Chapter 7. The Tying It All Together section uses
arrays to create a game of Rock, Paper, Scissors between a human player and the computer.
Preface xxi

Chapter 9: Searching, Sorting, and Algorithm Analysis


Here the student learns the basics of searching for information stored in arrays and of
sorting arrays , including arrays of objects. The chapter covers the Linear Search, Binary
Search, Bubble Sort, and Selection Sort algo rithm s and has an optional section on
so rtin g and search ing STL vecto rs. A brief int rod uction to algorithm analysis is
included, and students are shown how to determine which of two algorithms is more
efficient . Thi s chapter's Tying It All T ogether section uses both a table lookup and a
searching algorithm to encode and decode secret messages.

Chapter 10: Pointers


Thi s chapter explains how to use pointers . T op ics include pointer arithmetic,
initialization of pointers , comparison of pointers, pointers and arrays, pointers
and funct ions, dynamic memory allocation , the new null pt r key word, and
more . A new section introduces smart pointers and shows how they can be used
to avoid memory leaks. Th e Tying It All T oget her section demonstrates the use of
pointers to access library data struct ures and fun ctions that ret urn calendar and
wall cloc k time.

Chapter 11: More About Classes and Object -Oriented Programming


This chapter contin ues the study of classes and object-oriented programming, covering
more advanced topics such as inheritan ce and object aggregat ion and compos ition.
Other topics include constant member functions , static members, friends, memberwise
assignment, copy constructors, object type conversion operators, convert constr uctors,
operator overloading, move constr uctors, and move assignment operators . A new
section introduces function objects and the C++ll lambda expressions. The Tying It
All Together section brings together the concepts of inheritance and convert constr uctors
to build a program that formats the contents of an array to form an HTML tab le for
display on a Web site.

Chapter 12: More on (-Strings and the string Class


Thi s chapter covers standard library functions for working with characters and
C-strings, as well as materia l on str i ng class functions , functions in the new C++11
string library, and new overloaded to_st ring functions for converting numeric
values to str i ng objects . Th e Tying It All T ogether section shows students how to
access string -based program environments to obtain information about the computer
and the network on which the program is runnin g.

Chapter 13: Advanced File and 1/ 0 Operations


Thi s chapte r intr oduces more advanced topics for work ing with sequential access
text files and introduces random access and binary files . Various modes for open -
ing files are disc ussed, as well as the many methods for reading and writing their
contents. Th e Tying It All T oget her program app lies many of the techniques
covered in the chapte r to merge two text files into an HTML doc ument for display
on the Web , with different colors used to illustrate which file each piece of data
came from .
xxii Preface

Chapter 14: Recursion


In this chapter recursion is defined and demonstrated . A visual trace of recursive calls
is provided, and recursive applications are discussed . Many recursive algorithms are
presented, includ ing recursive functions for computing factorials, finding a greatest
common denom inator (GCD), performing a binary search, sorting using QuickSort,
and solving the famous Towers of Hanoi problem . For students who need more
challenge, there is a section on exhaustive and enumeration algorithm s. The Tying It
All Together section uses recursion to evaluate prefix expressions .

Chapter 15: Polymorphism and Virtual Functions


The study of classes and object -oriented programming continues in this chapter with
the introduction of more advanced concepts such as polymorphism and virtual
functions. Information is also presented on abstract base classes, pure virtual functions,
type compatibi lity within an inheritance hierarchy, and virtua l inheritance . The Tying
It All Together section illustrates the use of inheritance and polymorphism to display
and animate graphica l images.

Chapter 16: Exceptions, Templates, and the Standard Template


Library (STL)
Here the student learns to develop enhanced error trapping techniques using exceptions.
Discussion then turns to using funct ion and class templates to create gener ic code .
Finally, the student is introduced to the containers, iterators, and algorithms offered by
the Standard Template Library (STL). The Tying It All Together section uses various
conta iners in the Standard Template Librar y to create an educational children's game.

Chapter 17: Linked Lists


This chapter introduces concepts and techniques needed to work with lists. A linked list
ADT is developed, and the student learns how to create and destroy a list, as well as to write
functions to insert, append, and delete nodes, to traverse the list, and to search for a specific
node. A linked list class template is also demonstrated. The Tying It All Together section
brings together many of the most important concepts of OOP by using objeets, inheritance,
and polymorphism in conjunction with the STL list class to animate a collection of images.

Chapter 18: Stacks and Queues


In this chapter the student learns to create and use stat ic and dynamic stacks and queues.
Th e operations of stacks and queues are defined, and templates for each ADT are
demonstrated . The stat ic array -based stack uses exception -handling to handle stack
overflow and und erflow, providing a realistic and natural example of defining, throwing,
and catching except ions . The Tying It All Together section discusses strateg ies for
evaluating postfix expressions and uses a stack to convert a postfix expression to infix.

Chapter 19: Binary Trees


This chapter covers the binary tree ADT and demonstrates many binary tree operat ions.
The student learns to traverse a tree, insert, delete, and replace elements, search for a
particular element, and destroy a tree. The Tying It All Together section introduces a
tree structure versatile enough to create genealogy trees.
Another random document with
no related content on Scribd:
THE FREEBOOTER OF LOCHABER.

By Sir Thomas Dick Lauder.

Towards the end of the seventeenth century, there lived a certain


notorious freebooter, in the county of Moray, a native of Lochaber, of
the name of Cameron, but who was better known by his cognomen of
Padrig Mac-an-Ts’agairt, which signifies, “Peter, the Priest’s Son.”
Numerous were the “creachs,” or robberies of cattle on a great scale,
driven by him from Strathspey. But he did not confine his
depredations to that country; for, some time between the years 1690
and 1695, he made a clean sweep of the cattle from the rich pastures
of the Aird, the territory of the Frasers. That he might put his
pursuers on a wrong scent, he did not go directly towards Lochaber,
but, crossing the river Ness at Lochend, he struck over the mountains
of Strathnairn and Strathdearn, and ultimately encamped behind a
hill above Duthel, called, from a copious spring on its summit, Cairn-
an-Sh’uaran, or the Well Hill. But, notwithstanding all his
precautions, the celebrated Simon Lord Lovat, then chief of the
Frasers, discovered his track, and despatched a special messenger to
his father-in-law, Sir Ludovick Grant of Grant, begging his aid in
apprehending Mac-an-Ts’agairt, and recovering the cattle.
It so happened that there lived at this time, on the laird of Grant’s
ground, a man also called Cameron, surnamed Mugach More, of
great strength and undaunted courage; he had six sons and a
stepson, whom his wife, formerly a woman of light character, had
before her marriage with Mugach, and, as they were all brave, Sir
Ludovick applied to them to undertake the recapture of the cattle. Sir
Ludovic was not mistaken in the man. The Mugach no sooner
received his orders, than he armed himself and his little band, and
went in quest of the freebooter, whom he found in the act of cooking
a dinner from part of the spoil. The Mugach called on Padrig and his
men to surrender, and they, though numerous, dreading the well-
known prowess of their adversary, fled to the opposite hills, their
chief threatening bloody vengeance as he went. The Mugach drove
the cattle to a place of safety, and watched them till their owners
came to recover them.
Padrig did not utter his threats without the fullest intention of
carrying them into effect. In the latter end of the following spring, he
visited Strathspey with a strong party, and waylaid the Mugach, as he
and his sons were returning from working at a small patch of land he
had on the brow of a hill, about half-a-mile above his house. Padrig
and his party concealed themselves in a thick covert of underwood,
through which they knew that the Mugach and his sons must pass;
but seeing their intended victims well-armed, the cowardly assassins
lay still in their hiding-place, and allowed them to pass, with the
intention of taking a more favourable opportunity for their purpose.
That very night they surprised and murdered two of the sons, who,
being married, lived in separate houses, at some distance from their
father’s; and, having thus executed so much of their diabolical
purpose, they surrounded the Mugach’s cottage.
No sooner was his dwelling attacked, than the brave Mugach,
immediately guessing who the assailants were, made the best
arrangements for defence that time and circumstances permitted.
The door was the first point attempted; but it was strong, and he and
his four sons placed themselves behind it, determined to do bloody
execution the moment it should be forced. Whilst thus engaged, the
Mugach was startled by a noise above the rafters, and, looking up, he
perceived, in the obscurity, the figure of a man half through a hole in
the wattled roof. Eager to despatch his foe as he entered, he sprang
upon a table, plunged his sword into his body, and down fell—his
stepson, whom he had ever loved and cherished as one of his own
children! The youth had been cutting his way through the roof, with
the intention of attacking Padrig from above, and so creating a
diversion in favour of those who were defending the door. The brave
young man lived no longer than to say, “Dear father, I fear you have
killed me!”
For a moment the Mugach stood petrified with horror and grief,
but rage soon usurped the place of both. “Let me open the door!” he
cried, “and revenge his death, by drenching my sword in the blood of
the villain!” His sons clung around him, to prevent what they
conceived to be madness, and a strong struggle ensued between
desperate bravery and filial duty; whilst the Mugach’s wife stood
gazing on the corpse of her first-born son, in an agony of contending
passions, being ignorant from all she had witnessed but that the
young man’s death had been wilfully wrought by her husband. “Hast
thou forgotten our former days?” cried the wily Padrig, who saw the
whole scene through a crevice in the door. “How often hast thou
undone thy door to me, and wilt thou not open it now, to give me
way to punish him who has, but this moment, so foully slain thy
beloved son?” Ancient recollections, and present affliction, conspired
to twist her to his purpose. The struggle and altercation between the
Mugach and his sons still continued. A frenzy seized on the unhappy
woman; she flew to the door, undid the bolt, and Padrig and his
assassins rushed in.
The infuriated Mugach no sooner beheld his enemy enter, than he
sprang at him like a tiger, grasped him by the throat, and dashed him
to the ground. Already was his vigorous sword-arm drawn back, and
his broad claymore was about to find a passage to the traitor’s heart,
when his faithless wife, coming behind him, threw over it a large
canvas winnowing-sheet, and, before he could extricate the blade
from the numerous folds, Padrig’s weapon was reeking in the best
heart’s-blood of the bravest Highlander that Strathspey could boast
of. His four sons, who had witnessed their mother’s treachery, were
paralyzed. The unfortunate woman herself, too, stood stupified and
appalled. But she was quickly recalled to her senses by the active
clash of the swords of Padrig and his men. “Oh, my sons, my sons!”
she cried; “spare my boys!” But the tempter needed her services no
longer,—she had done his work. She was spurned to the ground and
trampled under foot by those who soon strewed the bloody floor
around her with the lifeless corpses of her brave sons.
Exulting in the full success of this expedition of vengeance, Mac-
an-Ts’agairt beheaded the bodies, and piled the heads in a heap on
an oblong hill that runs parallel to the road on the east side of Carr
Bridge, from which it is called Tom-nan-Cean, the Hill of the Heads.
Scarcely was he beyond the reach of danger, than his butchery was
known at the Castle Grant, and Sir Ludovick immediately offered a
great reward for his apprehension; but Padrig, who had anticipated
some such thing, fled to Ireland, where he remained for seven years.
But the restlessness of the murderer is well known, and Padrig felt it
in all its horrors. Leaving his Irish retreat, he returned to Lochaber.
By a strange accident, a certain Mungo Grant, of Muckrach, having
had his cattle and horses carried away by some thieves from that
quarter, pursued them hot foot, recovered them, and was on his way
returning with them, when, to his astonishment, he met Padrig Mac-
an-Ts’agairt, quite alone in a narrow pass, on the borders of his
native country. Mungo instantly seized and made a prisoner of him.
But his progress with his beasts was tedious; and as he was entering
Strathspey at Lag-na-caillich, about a mile to the westward of
Aviemore, he espied twelve desperate men, who, taking advantage of
his slow march, had crossed the hills to gain the pass before him, for
the purpose of rescuing Padrig. But Mungo was not to be daunted.
Seeing them occupying the road in his front, he grasped his prisoner
with one hand, and brandishing his dirk with the other, he advanced
in the midst of his people and animals, swearing potently that the
first motion at an attempt at rescue by any one of them should be the
signal for his dirk to drink the life’s-blood of Padrig Mac-an-
Ts’agairt. They were so intimidated by his boldness that they allowed
him to pass without assault, and left their friend to his fate. Padrig
was forthwith carried to Castle Grant. But the remembrance of the
Mugach’s murder had been by this time much obliterated by many
events little less strange, and the laird, unwilling to be troubled with
the matter, ordered Mungo and his prisoner away.
Disappointed and mortified, Mungo and his party were returning
with their captive, discussing, as they went, what they had best do
with him. “A fine reward we have had for all our trouble!” said one.
“The laird may catch the next thief her nainsel, for Donald!” said
another. “Let’s turn him loose!” said a third. “Ay, ay,” said a fourth;
“what for wud we be plaguing oursels more wi’ him?” “Yes, yes!
brave, generous men!” said Padrig, roused by a sudden hope of life
from the moody dream of the gallows-tree in which he had been
plunged, whilst he was courting his mournful muse to compose his
own lament, that he might die with an effect striking, as all the
events of his life had been. “Yes, brave men, free me from these
bonds! It is unworthy of Strathspey men,—it is unworthy of Grants to
triumph over a fallen foe! Those whom I killed were no clansmen of
yours, but recreant Camerons, who betrayed a Cameron! Let me go
free, and that reward of which you have been disappointed shall be
quadrupled for sparing my life.” Such words as these, operating on
minds so much prepared to receive them favourably, had well-nigh
worked their purpose. But “No!” said Muckrach sternly, “it shall
never be said that a murderer escaped from my hands. Besides, it
was just so that he fairly spake the Mugach’s false wife. But did he
spare her sons on that account? If ye let him go, my men, the fate of
the Mugach may be ours; for what bravery can stand against
treachery and assassination?” This opened an entirely new view of
the question to Padrig’s rude guards, and the result of the conference
was that they resolved to take him to Inverness, and to deliver him
up to the sheriff.
As they were pursuing their way up the south side of the river
Dulnan, the hill of Tom-nan-Cean appeared on that opposite to
them. At sight of it the whole circumstances of Padrig’s atrocious
deed came fresh in to their minds. It seemed to cry on them for
justice, and with one impulse they shouted out, “Let him die on the
spot where he did the bloody act!” Without a moment’s farther delay,
they determined to execute their new resolution. But on their way
across the plain, they happened to observe a large fir tree, with a
thick horizontal branch growing at right angles from the trunk, and
of a sufficient height from the ground to suit their purpose; and
doubting if they might find so convenient a gallows where they were
going, they at once determined that here Padrig should finish his
mortal career. The neighbouring birch thicket supplied them with
materials for making a withe; and whilst they were twisting it, Padrig
burst forth in a flood of Gaelic verse, which his mind had been
accumulating by the way. His song and the twig rope that was to
terminate his existence were spun out and finished at the same
moment, and he was instantly elevated to a height equally beyond his
ambition and his hopes.
AN HOUR IN THE MANSE.

By Professor Wilson.

In a few weeks the annual sacrament of the Lord’s Supper was to


be administered in the parish of Deanside; and the minister,
venerable in old age, of authority by the power of his talents and
learning, almost feared for his sanctity, yet withal beloved for
gentleness and compassion that had never been found wanting,
when required either by the misfortunes or errors of any of his flock,
had delivered for several successive Sabbaths, to full congregations,
sermons on the proper preparation of communicants in that awful
ordinance. The old man was a follower of Calvin; and many, who had
listened to him with a resolution in their hearts to approach the table
of the Redeemer, felt so awe-stricken and awakened at the
conclusion of his exhortations, that they gave their souls another
year to meditate on what they had heard, and by a pure and humble
course of life, to render themselves less unworthy to partake the
mysterious and holy bread and wine.
The good old man received in the manse, for a couple of hours
every evening, such of his parishioners as came to signify their wish
to partake of the sacrament; and it was then noted, that, though he in
nowise departed, in his conversation with them at such times, from
the spirit of those doctrines which he had delivered from the pulpit,
yet his manner was milder, and more soothing, and full of
encouragement; so that many who went to him almost with quaking
hearts, departed in tranquillity and peace, and looked forward to that
most impressive and solemn act of the Christian faith with calm and
glad anticipation. The old man thought, truly and justly, that few, if
any, would come to the manse, after having heard him in the kirk,
without due and deep reflection; and therefore, though he allowed
none to pass through his hands without strict examination, he spoke
to them all benignly, and with that sort of paternal pity which a
religious man, about to leave this life, feels towards all his brethren
of mankind, who are entering upon, or engaged in, its scenes of
agitation, trouble, and danger.
On one of those evenings, the servant showed into the minister’s
study a tall, bold-looking, dark-visaged man, in the prime of life,
who, with little of the usual courtesy, advanced into the middle of the
room, and somewhat abruptly declared the sacred purpose of his
visit. But before he could receive a reply, he looked around and
before him; and there was something so solemn in the old minister’s
appearance, as he sat like a spirit, with his unclouded eyes fixed upon
the intruder, that that person’s countenance fell, and his heart was
involuntarily knocking against his side. An old large Bible, the same
that he read from in the pulpit, was lying open before him. One
glimmering candle showed his beautiful and silvery locks falling over
his temples, as his head half stooped over the sacred page; a dead
silence was in the room dedicated to meditation and prayer; the old
man, it was known, had for some time felt himself to be dying, and
had spoken of the sacrament of this summer as the last he could ever
hope to administer; so that altogether, in the silence, the dimness,
the sanctity, the unworldliness of the time, the place, and the being
before him, the visitor stood like one abashed and appalled; and
bowing more reverently, or at least respectfully, he said, with a
quivering voice, “Sir, I come for your sanction to be admitted to the
table of our Lord.”
The minister motioned to him with his hand to sit down; and it
was a relief to the trembling man to do so, for he was in the presence
of one who, he felt, saw into his heart. A sudden change from
hardihood to terror took place within his dark nature; he wished
himself out of the insupportable sanctity of that breathless room;
and a remorse, that had hitherto slept, or been drowned within him,
now clutched his heartstrings, as if with an alternate grasp of frost
and fire, and made his knees knock against each other where he sat,
and his face pale as ashes.
“Norman Adams, saidst thou that thou wilt take into that hand,
and put into those lips, the symbol of the blood that was shed for
sinners, and of the body that bowed on the cross, and then gave up
the ghost? If so, let us speak together, even as if thou wert
communing with thine own heart. Never again may I join in that
sacrament, for the hour of my departure is at hand. Say, wilt thou eat
and drink death to thine immortal soul?”
The terrified man found strength to rise from his seat, and,
staggering towards the door, said, “Pardon, forgive me!—I am not
worthy.”
“It is not I who can pardon, Norman. That power lies not with
man; but sit down—you are deadly pale—and though, I fear, an ill-
living and a dissolute man, greater sinners have repented and been
saved. Approach not now the table of the Lord, but confess all your
sins before Him in the silence of your own house, and upon your
naked knees on the stone-floor every morning and every night; and if
this you do faithfully, humbly, and with a contrite heart, come to me
again when the sacrament is over, and I will speak words of comfort
to you (if then I am able to speak)—if, Norman, it should be on my
deathbed. This will I do for the sake of thy soul, and for the sake of
thy father, Norman, whom my soul loved, and who was a support to
me in my ministry for many long, long years, even for two score and
ten, for we were at school together; and had your father been living
now, he would, like myself, have this very day finished his eighty-
fifth year. I send you not from me in anger, but in pity and love. Go,
my son, and this very night begin your repentance, for if that face
speak the truth, your heart must be sorely charged.”
Just as the old man ceased speaking, and before the humble, or at
least affrighted culprit had risen to go, another visitor of a very
different kind was shown into the room—a young, beautiful girl,
almost shrouded in her cloak, with a sweet pale face, on which
sadness seemed in vain to strive with the natural expression of the
happiness of youth.
“Mary Simpson,” said the kind old man, as she stood with a timid
courtesy near the door, “Mary Simpson, approach, and receive from
my hands the token for which thou comest. Well dost thou know the
history of thy Saviour’s life, and rejoicest in the life and immortality
brought to light by the gospel. Young and guileless, Mary, art thou;
and dim as my memory now is of many things, yet do I well
remember the evening, when first beside my knee, thou heardst read
how the Divine Infant was laid in a manger, how the wise men from
the East came to the place of His nativity, and how the angels were
heard singing in the fields of Bethlehem all the night long.”
Alas! every word that had thus been uttered sent a pang into the
poor creature’s heart, and, without lifting her eyes from the floor,
and in a voice more faint and hollow than belonged to one so young,
she said, “O sir! I come not as an intending communicant; yet the
Lord my God knows that I am rather miserable than guilty, and He
will not suffer my soul to perish, though a baby is now within me, the
child of guilt, and sin, and horror. This, my shame, come I to tell you;
but for the father of my babe unborn, cruel though he has been to
me,—oh! cruel, cruel, indeed,—yet shall his name go down with me
in silence to the grave. I must not, must not breathe his name in
mortal ears; but I have looked round me in the wide moor, and when
nothing that could understand was by, nothing living but birds, and
bees, and the sheep I was herding, often have I whispered his name
in my prayers, and beseeched God and Jesus to forgive him all his
sins.”
At these words, of which the passionate utterance seemed to
relieve her heart, and before the pitying and bewildered old man
could reply, Mary Simpson raised her eyes from the floor, and
fearing to meet the face of the minister, which had heretofore never
shone upon her but with smiles, and of which the expected frown
was to her altogether insupportable, she turned them wildly round
the room, as if for a dark resting-place, and beheld Norman Adams
rooted to his seat, leaning towards her with his white, ghastly
countenance, and his eyes starting from their sockets, seemingly in
wrath, agony, fear, and remorse. That terrible face struck poor Mary
to the heart, and she sank against the wall, and slipped down,
shuddering, upon a chair.
“Norman Adams, I am old and weak, but do you put your arm
round that poor lost creature, and keep her from falling down on the
hard floor. I hear it is a stormy night, and she has walked some miles
hither; no wonder she is overcome. You have heard her confession,
but it was not meant for your ear; so, till I see you again, say nothing
of what you have now heard.”
“O sir! a cup of water, for my blood is either leaving my heart
altogether, or it is drowning it. Your voice, sir, is going far, far away
from me, and I am sinking down. Oh, hold me!—hold me up! Is it a
pit into which I am falling?—Saw I not Norman Adams?—Where is
he now?”
The poor maiden did not fall off the chair, although Norman
Adams supported her not; but her head lay back against the wall, and
a sigh, long and dismal, burst from her bosom, that deeply affected
the old man’s heart, but struck that of the speechless and motionless
sinner, like the first toll of the prison bell that warns the felon to
leave his cell and come forth to execution.
The minister fixed a stern eye upon Norman, for, from the poor
girl’s unconscious words, it was plain that he was the guilty wretch
who had wrought all this misery. “You knew, did you not, that she
had neither father nor mother, sister nor brother, scarcely one
relation on earth to care for or watch over her; and yet you have used
her so? If her beauty was a temptation unto you, did not the sweet
child’s innocence touch your hard and selfish heart with pity? or her
guilt and grief must surely now wring it with remorse. Look on her—
white, cold, breathless, still as a corpse; and yet, thou bold bad man,
thy footsteps would have approached the table of thy Lord!”
The child now partly awoke from her swoon, and her dim opening
eyes met those of Norman Adams. She shut them with a shudder,
and said, sickly and with a quivering voice, “Oh spare, spare me,
Norman! Are we again in that dark, fearful wood? Tremble not for
your life on earth, Norman, for never, never will I tell to mortal ears
that terrible secret; but spare me, spare me, else our Saviour, with all
His mercy, will never pardon your unrelenting soul. These are cruel-
looking eyes; you will not surely murder poor Mary Simpson,
unhappy as she is, and must for ever be—yet life is sweet! She
beseeches you on her knees to spare her life!”—and, in the intense
fear of phantasy, the poor creature struggled off the chair, and fell
down indeed in a heap at his feet.
“Canst thou indeed be the son of old Norman Adams, the
industrious, the temperate, the mild, and the pious—who so often sat
in this very room which thy presence has now polluted, and spake
with me on the mysteries of life and of death? Foul ravisher, what
stayed thy hand from the murder of that child, when there were none
near to hear her shrieks in the dark solitude of the great pine-wood?”
Norman Adams smote his heart and fell down too on his knees
beside the poor ruined orphan. He put his arm round her, and,
raising her from the floor, said, “No, no, my sin is great, too great for
Heaven’s forgiveness; but, oh sir! say not—say not that I would have
murdered her; for, savage as my crime was, yet may God judge me
less terribly than if I had taken her life.”
In a little while they were both seated with some composure, and
silence was in the room. No one spoke, and the old grayhaired man
sat with his eyes fixed, without reading, on the open Bible. At last he
broke silence with these words out of Isaiah, that seemed to have
forced themselves on his heedless eyes:—“Though your sins be as
scarlet, they shall be as white as snow: though they be red like
crimson, they shall be as wool.”
Mary Simpson wept aloud at these words, and seemed to forget
her own wrongs and grief in commiseration of the agonies of
remorse and fear that were now plainly preying on the soul of the
guilty man. “I forgive you, Norman, and will soon be out of the way,
no longer to anger you with the sight of me.” Then, fixing her
streaming eyes on the minister, she besought him not to be the
means of bringing him to punishment and a shameful death, for that
he might repent, and live to be a good man and respected in the
parish; but that she was a poor orphan for whom few cared, and who,
when dead, would have but a small funeral.
“I will deliver myself up into the hands of justice,” said the
offender, “for I do not deserve to live. Mine was an inhuman crime,
and let a violent and shameful death be my doom.”
The orphan girl now stood up as if her strength had been restored,
and stretching out her hands passionately, with a flow of most
affecting and beautiful language, inspired by a meek, single, and
sinless heart that could not bear the thought of utter degradation and
wretchedness befalling any one of the rational children of God,
implored and beseeched the old man to comfort the sinner before
them, and promise that the dark transaction of guilt should never
leave the concealment of their own three hearts. “Did he not save the
lives of two brothers once who were drowning in that black mossy
loch, when their own kindred, at work among the hay, feared the
deep sullen water, and all stood aloof shuddering and shaking, till
Norman Adams leapt in to their rescue, and drew them by the
dripping hair to the shore, and then lay down beside them on the
heather as like to death as themselves? I myself saw it done; I myself
heard their mother call down the blessing of God on Norman’s head,
and then all the haymakers knelt down and prayed. When you, on
the Sabbath, returned thanks to God for that they were saved, oh!
kind sir, did you not name, in the full kirk, him who, under
Providence, did deliver them from death, and who, you said, had
thus showed himself to be a Christian indeed? May his sin against
me be forgotten, for the sake of those two drowning boys, and their
mother, who blesses his name unto this day.”
From a few questions solemnly asked, and solemnly answered, the
minister found that Norman Adams had been won by the beauty and
loveliness of this poor orphan shepherdess, as he had sometimes
spoken to her when sitting on the hill-side with her flock, but that
pride had prevented him from ever thinking of her in marriage. It
appeared that he had also been falsely informed, by a youth whom
Mary disliked for his brutal and gross manners, that she was not the
innocent girl that her seeming simplicity denoted. On returning from
a festive meeting, where this abject person had made many mean
insinuations against her virtue, Norman Adams met her returning to
her master’s house, in the dusk of the evening, on the footpath
leading through a lonely wood; and, though his crime was of the
deepest dye, it seemed to the minister of the religion of mercy, that
by repentance, and belief in the atonement that had once been made
for sinners, he, too, might perhaps hope for forgiveness at the throne
of God.
“I warned you, miserable man, of the fatal nature of sin, when first
it brought a trouble over your countenance, and broke in upon the
peaceful integrity of your life. Was not the silence of the night often
terrible to you, when you were alone in the moors, and the whisper of
your own conscience told you, that every wicked thought was
sacrilege to your father’s dust? Step by step, and almost
imperceptibly, perhaps, did you advance upon the road that leadeth
to destruction; but look back now, and what a long dark journey have
you taken, standing, as you are, on the brink of everlasting death!
Once you were kind, gentle, generous, manly, and free; but you
trusted to the deceitfulness of your own heart; you estranged yourself
from the house of the God of your fathers; and what has your nature
done for you at last, but sunk you into a wretch—savage, selfish,
cruel, cowardly, and in good truth a slave? A felon are you, and
forfeited to the hangman’s hands. Look on that poor innocent child,
and think what is man without God. What would you give now, if the
last three years of your reckless life had been passed in a dungeon
dug deep into the earth, with hunger and thirst gnawing at your
heart, and bent down under a cartload of chains? Yet look not so
ghastly, for I condemn you not utterly; nor, though I know your guilt,
can I know what good may yet be left uncorrupted and
unextinguished in your soul. Kneel not to me, Norman; fasten not so
your eyes upon me; lift them upwards, and then turn them in upon
your own heart, for the dreadful reckoning is between it and God.”
Mary Simpson had now recovered all her strength, and she knelt
down by the side of the groaner. Deep was the pity she now felt for
him, who to her had shown no pity; she did not refuse to lay her light
arm tenderly upon his neck. Often had she prayed to God to save his
soul, even among her rueful sobs of shame in the solitary glens; and
now that she beheld his sin punished with a remorse more than he
could bear, the orphan would have willingly died to avert from his
prostrate head the wrath of the Almighty.
The old man wept at the sight of so much innocence, and so much
guilt, kneeling together before God, in strange union and fellowship
of a common being. With his own fatherly arms he lifted up the
orphan from her knees, and said, “Mary Simpson, my sweet and
innocent Mary Simpson, for innocent thou art, the elders will give
thee a token, that will, on Sabbath-day, admit thee (not for the first
time, though so young) to the communion-table. Fear not to
approach it; look at me, and on my face, when I bless the elements,
and be thou strong in the strength of the Lord. Norman Adams,
return to your home. Go into the chamber where your father died.
Let your knees wear out the part of the floor on which he kneeled. It
is somewhat worn already; you have seen the mark of your father’s
knees. Who knows, but that pardon and peace may descend from
Heaven upon such a sinner as thou? On none such as thou have mine
eyes ever looked, in knowledge, among all those who have lived and
died under my care, for three generations. But great is the unknown
guilt that may be hidden even in the churchyard of a small quiet
parish like this. Dost thou feel as if God-forsaken? Or, oh! say it unto
me, canst thou, my poor son, dare to hope for repentance?”
The pitiful tone of the old man’s trembling voice, and the motion
of his shaking and withered hands, as he lifted them up almost in an
attitude of benediction, completed the prostration of that sinner’s
spirit. All his better nature, which had too long been oppressed under
scorn of holy ordinances, and the coldness of infidelity, and the
selfishness of lawless desires that insensibly harden the heart they do
not dissolve, now struggled to rise up and respect its rights. “When I
remember what I once was, I can hope—when I think what I now am,
I only, only fear.”
A storm of rain and wind had come on, and Mary Simpson slept in
the manse that night. On the ensuing Sabbath she partook of the
sacrament. A woeful illness fell upon Norman Adams; and then for a
long time no one saw him, or knew where he had gone. It was said
that he was in a distant city, and that he was a miserable creature,
that never again could look upon the sun. But it was otherwise
ordered. He returned to his farm, greatly changed in face and person,
but even yet more changed in spirit.
The old minister had more days allotted to him than he had
thought, and was not taken away for some summers. Before he died,
he had reason to know that Norman Adams had repented in tears of
blood, in thoughts of faith, and in deeds of charity; and he did not
fear to admit him, too, in good time, to the holy ordinance, along
with Mary Simpson, then his wife, and the mother of his children.
THE WARDEN OF THE MARCHES:
A TRADITIONARY STORY OF ANNANDALE.

The predatory incursions of the Scots and English borderers, on


each other’s territories, are known to every one in the least
acquainted with either the written or traditional history of his
country. These were sometimes made by armed and numerous
bodies, and it was not uncommon for a band of marauders to take
advantage of a thick fog or a dark night for plundering or driving
away the cattle, with which they soon escaped over the border, where
they were generally secure. Such incursions were so frequent and
distressing to the peaceable and well-disposed inhabitants that they
complained loudly to their respective governments; in consequence
of which some one of the powerful nobles residing on the borders
was invested with authority to suppress these depredations, under
the title of Warden of the Marches. His duty was to protect the
frontier, and alarm the country by firing the beacons which were
placed on the heights, where they could be seen at a great distance,
as a warning to the people to drive away their cattle, and, collecting
in a body, either to repel or pursue the invaders, as circumstances
might require. The wardens also possessed a discretionary power in
such matters as came under their jurisdiction. The proper discharge
of this important trust required vigilance, courage, and fidelity, but it
was sometimes committed to improper hands, and consequently the
duty was very improperly performed.
In the reign of James V. one of these wardens was Sir John
Charteris of Amisfield, near Dumfries, a brave but haughty man, who
sometimes forgot his important trust so far as to sacrifice his public
duties to his private interests.
George Maxwell was a young and respectable farmer in
Annandale, who had frequently been active in repressing the petty
incursions to which that quarter of the country was exposed. Having
thereby rendered himself particularly obnoxious to the English
borderers, a strong party was formed, which succeeded in despoiling
him, by plundering his house and driving away his whole live stock.
At the head of a large party he pursued and overtook the “spoil-
encumbered foe;” a fierce and bloody contest ensued, in which
George fell the victim of a former feud, leaving his widow, Marion, in
poverty, with her son Wallace, an only child in the tenth year of his
age. By the liberality of her neighbours, the widow was replaced in a
small farm; but by subsequent incursions she was reduced to such
poverty that she occupied a small cottage, with a cow, which the
kindness of a neighbouring farmer permitted to pasture on his fields.
This, with the industry and filial affection of her son, now in his
twentieth year, enabled her to live with a degree of comfort and
contented resignation.
With a manly and athletic form, Wallace Maxwell inherited the
courage of his father, and the patriotic ardour of the chieftain after
whom he had been named; and Wallace had been heard to declare,
that although he could not expect to free his country from the
incursions of the English borderers, he trusted he should yet be able
to take ample vengeance for the untimely death of his father.
But although his own private wrongs and those of his country had
a powerful influence on the mind of Wallace Maxwell, yet his heart
was susceptible of a far loftier passion.
His fine manly form and graceful bearing had attractions for many
a rural fair; and he would have found no difficulty in matching with
youthful beauty considerably above his own humble station. But his
affections were fixed on Mary Morrison, a maiden as poor in worldly
wealth as himself; but nature had been more than usually indulgent
to her in a handsome person and fine features; and, what was of
infinitely more value, her heart was imbued with virtuous principles,
and her mind better cultivated than could have been expected from
her station in life. To these accomplishments were superadded a
native dignity, tempered with modesty, and a most winning
sweetness of manner. Mary was the daughter of a man who had seen
better days; but he was ruined by the incursions of the English
borderers; and both he and her mother dying soon after, Mary was
left a helpless orphan in the twentieth year of her age. Her beauty
procured her many admirers; and her unprotected state (for she had
no relations in Annandale) left her exposed to the insidious
temptations of unprincipled villainy; but they soon discovered that
neither flattery, bribes, nor the fairest promises, had the slightest
influence on her spotless mind. There were many, however, who
sincerely loved her, and made most honourable proposals; among
whom was Wallace Maxwell, perhaps the poorest of her admirers,
but who succeeded in gaining her esteem and affection. Mary and he
were fellow-servants to the farmer from whom his mother had her
cottage; and, on account of the troublesome state of the country,
Wallace slept every night in his mother’s house as her guardian and
protector. Mary and he were about the same age, both in the bloom
of youthful beauty; but both had discrimination to look beyond
external attractions; and, although they might be said to live in the
light of each other’s eyes, reason convinced them that the time was
yet distant when it would be prudent to consummate that union
which was the dearest object of their wishes.
A foray had been made by the English, in which their leader, the
son of a rich borderer, had been made prisoner, and a heavy ransom
paid to Sir John, the warden, for his release. This the avaricious
warden considered a perquisite of his office; and it accordingly went
into his private pocket. Soon after this, the party who had resolved
on ruining Wallace Maxwell for his threats of vengeance, took
advantage of a thick fog during the day, succeeded by a dark night, in
making an incursion on Annandale, principally for the purpose of
capturing the young man. By stratagem they effected their purpose;
and the widow’s cow, and Wallace her son, were both carried off as
part of the spoil. The youth’s life might have been in considerable
danger, had his capture not been discovered by the man who had
recently paid a high ransom for his own son, and he now took instant
possession of Wallace, resolving that he should be kept a close
prisoner till ransomed by a sum equal to that paid to the warden.
It would be difficult, if not impossible, to say whether the grief of
Widow Maxwell for her son, or that of Mary Morrison for her lover,
was greatest. But early in the ensuing morning the widow repaired to
Amisfield, related the circumstance to Sir John, with tears
beseeching him, as the plunderers were not yet far distant, to
despatch his forces after them, and rescue her son, with the property
of which she had been despoiled, for they had carried off everything,
even to her bed-clothes.
Wallace Maxwell had some time before incurred the warden’s
displeasure, whose mind was not generous enough either to forget or
forgive. He treated Marion with an indifference approaching almost
to contempt, by telling her that it would be exceedingly improper to
alarm the country about such a trivial incident, to which every
person in that quarter was exposed; and although she kneeled to
him, he refused to comply with her request, and proudly turned
away.
With a heavy and an aching heart, the widow called on Mary
Morrison on her way home to her desolate dwelling, relating the
failure of her application, and uttering direful lamentations for the
loss of her son; all of which were echoed by the no less desponding
maiden.
In the anguish of her distress, Mary formed the resolution of
waiting on the warden, and again urging the petition which had
already been so rudely rejected. Almost frantic, she hastened to the
castle, demanding to see Sir John. Her person was known to the
porter, and he was also now acquainted with the cause of her present
distress; she therefore found a ready admission. Always beautiful,
the wildness of her air, the liquid fire which beamed in her eyes, from
which tears streamed over her glowing cheeks, and the perturbation
which heaved her swelling bosom, rendered her an object of more
than ordinary interest in the sight of the warden. She fell at his feet
and attempted to tell her melancholy tale; but convulsive sobs stifled
her utterance. He then took her unresisting hand, raised her up, led
her to a seat, and bade her compose herself before she attempted to
speak.
With a faltering tongue, and eyes which, like the lightning of
heaven, seemed capable of penetrating a heart of adamant, and in all
the energy and pathos of impassioned grief, she told her tale,—
imploring the warden, if he ever regarded his mother, or if capable of
feeling for the anguish of a woman, to have pity on them, and
instantly exert himself to restore the most dutiful of sons, and the
most faithful of lovers, to his humble petitioners, whose gratitude
should cease only with their lives.
“You are probably not aware,” said he, in a kindly tone, “of the
difficulty of gratifying your wishes. Wallace Maxwell has rendered
himself the object of vengeance to the English borderers; and, before
now, he must be in captivity so secure, that any measure to rescue
him by force of arms would be unavailing. But, for your sake, I will
adopt the only means which can restore him, namely, to purchase his
ransom by gold. But you are aware that it must be high, and I trust
your gratitude will be in proportion.”
“Everything in our power shall be done to evince our gratitude,”
replied the delighted Mary, a more animated glow suffusing her
cheek, and her eyes beaming with a brighter lustre,—“Heaven reward
you.”
“To wait for my reward from heaven, would be to give credit to one
who can make ready payment,” replied the warden. “You, lovely
Mary, have it in your power to make me a return, which will render
me your debtor, without in any degree impoverishing yourself;”—and
he paused, afraid or ashamed to speak the purpose of his heart. Such
is the power which virgin beauty and innocence can exert on the
most depraved inclinations.
Although alarmed, and suspecting his base design, such was the
rectitude of Mary’s guileless heart, that she could not believe the
warden in earnest; and starting from his proffered embrace, she with
crimson blushes replied, “I am sure, sir, your heart could never
permit you so far to insult a hapless maiden. You have spoken to try
my affection for Wallace Maxwell; let me therefore again implore you
to take such measures as you may think best for obtaining his
release;” and a fresh flood of tears flowed in torrents from her eyes,
while she gazed wistfully in his face, with a look so imploringly
tender, that it might have moved the heart of a demon.
With many flattering blandishments, and much artful sophistry,
he endeavoured to win her to his purpose; but perceiving that his
attempts were unavailing, he concluded thus:—“All that I have
promised I am ready to perform; but I swear by Heaven, that unless
you grant me the favour which I have so humbly solicited, Wallace
Maxwell may perish in a dungeon, or by the hand of his enemies; for
he shall never be rescued by me. Think, then, in time, before you
leave me, and for his sake, and your own future happiness, do not
foolishly destroy it for ever.”
With her eyes flashing indignant fire, and her bosom throbbing
with the anguish of insulted virtue, she flung herself from his hateful
embrace, and, rushing from his presence, with a sorrowful and
almost bursting heart, left the castle.
Widow Maxwell had a mind not easily depressed, and although in
great affliction for her son, did not despair of his release. She was
ignorant of Mary’s application to the warden, and had been revolving
in her mind the propriety of seeking an audience of the king, and
detailing her wrongs, both at the hands of the English marauders and
Sir John. She was brooding on this when Mary entered her cottage,
and, in the agony of despairing love and insulted honour, related the
reception she had met from the warden. The relation confirmed the
widow’s half formed resolution, and steeled her heart to its purpose.
After they had responded each other’s sighs, and mingled tears
together, the old woman proposed waiting on her friend the farmer,
declaring her intentions, and, if he approved of them, soliciting his
permission for Mary to accompany her.
The warden’s indolent neglect of duty was a subject of general
complaint; the farmer, therefore, highly approved of the widow’s
proposal, believing that it would not only procure her redress, but
might be of advantage to the country. He urged their speedy and
secret departure, requesting that whatever answer they received
might not be divulged till the final result was seen; and next
morning, at early dawn, the widow and Mary took their departure for
Stirling. King James was easy of access to the humblest of his
subjects; and the two had little difficulty in obtaining admission to
the royal presence. Widow Maxwell had in youth been a beautiful
woman, and, although her early bloom had passed, might still have
been termed a comely and attractive matron, albeit in the autumn of
life. In a word, her face was still such as would have recommended
her suit to the king, whose heart was at all times feelingly alive to the
attraction of female beauty. But, on the present occasion, although
she was the petitioner, the auxiliary whom she had brought, though
silent, was infinitely the more powerful pleader; for Mary might be
said to resemble the half-blown rose in the early summer, when its
glowing leaves are wet with the dews of morning. James was so
struck with their appearance, that, before they had spoken, he
secretly wished that their petitions might be such as he could with

You might also like