SlideShare a Scribd company logo
Absolute C++ 6th Edition Savitch Solutions
Manual install download
https://testbankfan.com/product/absolute-c-6th-edition-savitch-
solutions-manual/
Download more testbank from https://testbankfan.com
We believe these products will be a great fit for you. Click
the link to download now, or visit testbankfan.com
to discover even more!
Absolute C++ 6th Edition Savitch Test Bank
https://testbankfan.com/product/absolute-c-6th-edition-savitch-
test-bank/
Absolute C++ 5th Edition Savitch Solutions Manual
https://testbankfan.com/product/absolute-c-5th-edition-savitch-
solutions-manual/
Absolute C++ 5th Edition Savitch Test Bank
https://testbankfan.com/product/absolute-c-5th-edition-savitch-
test-bank/
Absolute Java 6th Edition Savitch Test Bank
https://testbankfan.com/product/absolute-java-6th-edition-
savitch-test-bank/
Absolute Java 5th Edition Walter Savitch Solutions
Manual
https://testbankfan.com/product/absolute-java-5th-edition-walter-
savitch-solutions-manual/
Absolute Java 5th Edition Walter Savitch Test Bank
https://testbankfan.com/product/absolute-java-5th-edition-walter-
savitch-test-bank/
Problem Solving with C++ 10th Edition Savitch Solutions
Manual
https://testbankfan.com/product/problem-solving-with-c-10th-
edition-savitch-solutions-manual/
Problem Solving with C++ 9th Edition Savitch Solutions
Manual
https://testbankfan.com/product/problem-solving-with-c-9th-
edition-savitch-solutions-manual/
Problem Solving with C++ 9th Edition Savitch Test Bank
https://testbankfan.com/product/problem-solving-with-c-9th-
edition-savitch-test-bank/
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
Chapter 6
Structures and Classes
Key Terms
structure
struct
structure tag
member name
where to place a structure definition
structure value
member value
member variable
reusing member names
structure variables in assignment statements
structure arguments
functions can return structures
class
object
member function
calling member functions
defining member functions
scope resolution operator
type qualifier
member variables in function definitions
data types and abstract types
encapsulation
private:
private member variable
public:
public member variable
accessor function
mutator function
interface
API
implementation
Brief Outline
6.1 Structures
Structure Types
Structures as Function Arguments
Initializing Structures
6.2 Classes
Defining Classes and Member Functions
Encapsulation
Public and Private Members
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
Accessor and Mutator Functions
Structures versus Classes
1. Introduction and Teaching Suggestions
In earlier chapters, we saw the array, the first of the C++ tools for creating data structures. The
other tools are the struct and the class. We saw that the array provides a homogeneous,
random access data structure. This chapter introduces tools to create heterogenous data
structures, namely the struct and class. While the struct and class are identical except for default
access, the text takes the didactic approach of first ignoring struct function members. This
chapter deals with the struct as C treats it. The text then develops the simpler ideas involved in
declaration and access for the struct. Then the machinery of class creation, protection
mechanisms and some ideas of encapsulation of functions with data are treated. Constructors are
left to Chapter 7.
2. Key Points
Structures and Structure Types. Historical note: The name struct in C++ is provided
primarily for backward compatibility with ANSI C. Suppose we declare a struct, as in:
struct B
{
int x;
int y;
};
The text points out that the identifier B is called the structure tag. The structure tag B carries full
type information. The tag B can be used as you would use any built-in type. The identifiers x and
y declared in the definition of struct B are called member names. The members are variables are
associated with any variable of struct type. You can declare a variable of type B by writing1
B u;
You can access member variables (as l-values) by writing
u.x = 1;
u.y = 2;
or (as r-values)
int p, q;
p = u.x;
q = u.y;
We said in the previous paragraph that the tag B can be used as you would use any built-in type.
You can pass a struct to a function as a parameter, use a struct as a function return type, and
declare arrays of variables of type struct.
1
Contrast this with the C usage, struct B u;, where the keyword struct must be used in the definition of a
structure variable. This use is permitted in C++ for backward compatibility with C.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
Our author points out that two identifiers that are declared to be of the same structure type may be
assigned, with member-wise assignment occurring.2
The critical issue here is that for assignment
compatibility the two structure variables must be declared with the same structure tag. In the
example that follows, the types are indistinguishable from the member structure within the struct.
However, C++ uses name equivalence for types, so the compiler looks at the tags in the
declarations rather than the structure to determine whether one struct variable may be assigned to
another. Example:
struct A
{
int x;
int y;
};
struct B
{
int x;
int y;
};
A u;
B v;
u = v; //type error: u and v are of different types
The error message from g++ 2.9.5 is:
// no match for 'A& = B&'
// candidates are: struct A& A::operator=(const A&)
Structures as Function Arguments. Since a structure tag is a type, the tag can be used as any other
type would be used. You can have arrays of structure objects, or function parameters that are call-by-value
or call-by-reference, and you can use a structure a type for the return type of a function.
Defining Classes and Member Functions. These remarks elaborate the ideas in the text on
class and the scope resolution operator, ::. A class definition (and a struct definition as well),
with the {}; define a scope within which variables and functions are defined. They are not
accessible outside without qualification by the object name and a dot operator . Member
functions are defined within a particular class, to be used by any object declared to be of that
class, again, only with qualification by being preceded by the object name and the dot operator.
To define a function whose prototype is given in a class we have to specify the scope of that
class within which the function is being defined. This is done with the class tag and scope
resolution operator.
To say:
returnTypeName class_tag::funcMemberName(argumentList)
{
//memberFunctionBody...
}
is to say "Within the scope of the class class_tag, define the function named funcMemberName
that has return type returnTypeName."
2
Member-wise assignment is the default for classes and structs. A former student of mine, John Gibson coined the
phrase, “Member UNWISE copy”. We will see that for classes with pointer members, member (un)wise copy is
almost never what you want.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
The data members belong to a particular object, and function members must be called on behalf
of that particular object. The object must be specified. The object is specified by using the dot
operator used after the object name, before the member name or function call. Sometimes we
may speak of the calling object.
Encapsulation. The notion of encapsulation means, “to collect together, as if to place in a
capsule”, from which we may infer the purpose, “to hide the details”. The text says a data type
has a set of values to be manipulated, and sets of operations to manipulate the values, but the
details are available to the user or client. A data type becomes an abstract data type if the client
does not have access to the implementation details.
Abstract Data Types. The notion of Abstract Data Type (ADT) has two players: the author of
the ADT and the client of the ADT. The client knows only what the ADT will do, not how the
ADT carries out its tasks. The author of the ADT knows only what the ADT will do for the
client, but nothing about the context within which the ADT is used by the client. Information
hiding is a two way hiding. The separation of implementation (known only to the class author)
and the interface (the contract between ADT author and client) is vital. The other side of the
coin, namely the concealment from the ADT author of the context within which the ADT will be
used, is equally vital. This prevents either author from writing code that would depend on the
internals written by the other programmer.
Separate compilation is necessary to a) concealing implementation details and b) assigning tasks
to several programmers in a team. The reason for leaving the interface and the implementation of
the ADTs in the client in the text is that we do not yet know anything about separate compilation.
Observe that the text almost always places declarations (prototypes) prior to use, then uses the
functions in the main function, then tucks the definitions away after the main function. This has
the effect of emphasizing separation of definition and declaration well before separate
compilation is seen by the student. This is worth mentioning to the student.
Public and Private Members. The data members of a class are part of the implementation, not
part of the interface. The function members intended for use by the client are the interface. There
may be helping functions for the implementation that would be inappropriate for the client to
use, and so are not part of the interface. Normally the interface is made available to the client and
the implementation is hidden.
A struct, by default, allows access to its members by any function. A class, by default, allows
access to its members only to those functions declared within the class. This default access in a
struct is called public, and the default access in a class is called private.
The keywords private and public help manage hiding the implementation and making the
interface available to the client. These keywords are used to modify the default access to
members of a class or struct. The keyword private is used to hide members. The effect of the
keyword private: extends from the keyword private: to the next instance of the keyword public:.
The effect of the keyword public: extends from the keyword public: up to the next instance of the
keyword private:.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
Accessor and Mutator Functions. It is the class author who writes the accessor and mutator
functions, so it is she who controls the access to the class data. If the data members were public,
any function has access in any way the client wishes. Data integrity will be compromised.
Structures versus Classes. This is the text’s “truth in advertising” section. Since this document
is for the instructor, little distinction between structs and classes is made here.
3. Tips
Hierarchical Structures. It is worth pointing out that the name spaces for hierarchical (or
nested) structures are separate. The same names can be used in the containing struct as are used
in the structure member. The same names can be used in two structures members at the same
level.
Example: Name space and hierarchical structure initialization
// file: ch6test2.cc
// purpose: test namespace in hierarchical structures
#include <iostream>
using namespace std;
struct A
{
int a;
int b;
};
struct B
{
A c;
int a;
int b;
};
int main()
{
A u = {1,2};
B v = {{3,4},4,5};
cout << "u.a = " << u.a << " u.b = " << u.b << endl;
cout << "v.c.a = " << v.c.a << " v.c.b = " << v.c.b
<< " v.a = " << v.a << " v.b = " << v.b << endl;
return 0;
}
This code compiles and runs as expected. The output is:
u.a = 1 u.b = 2
v.c.a = 3 v.c.b = 4 v.a = 4 v.b = 5
This is, of course, a "horrible example", designed to show a worst case. One would almost never
use the same identifiers in two structures while using a struct object as a member of another as
we do here. However, this does serve to illustrate the idea that the name spaces for two structures
are separate. (This is also true for classes as well.) In short, duplicating a member name where
needed won't break a program.
Initializing Structures. The previous example also illustrates that structure variables can be
assigned initial values using the curly brace notation.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
Separate Interface and Implementation. The interface provides the API and helps abstract the
implementation details from a user of the class. This allows a programmer to change the
implementation without having to change other parts of the program.
A Test for Encapsulation. If you can change the implementation of a class without requiring a
change to the client code, you have the implementation adequately encapsulated.
Thinking Objects. When programming with classes, data rather than algorithms takes center
stage. The difference is in the point of view compared to students that have never programmed
with objects before.
4. Pitfalls
Omitting the semicolon at the end of a struct or class definition. The text points out that a
structure definition is required to have a semicolon following the closing curly brace. The reason
is that it is possible to define a variable of the struct type by putting the identifier between the
closed curly brace, }, and the semicolon.
struct A
{
int a;
int b;
} c;
The variable c is of struct type A. With some compilers, this pitfall generates particularly
uninformative error messages. It will be quite helpful for the student to write several examples in
which the closing semicolon in a structure definition is deliberately omitted.
5. Programming Projects Answers
1. Class grading program
//ch6Prg1.cpp
#include <iostream>
using namespace std;
const int CLASS_SIZE = 5;
// Problem says this is for a class, rather than one student.
// Strategy: Attack for a single student, then do for an array of N
// students.
//Grading Program
//Policies:
//
// Two quizzes, 10 points each
// midterm and final exam, 100 points each
// Of grade, final counts 50%, midterm 25%, quizes25%
//
// Letter Grade is assigned:
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
// 90 or more A
// 80 or more B
// 70 or more C
// 60 or more D
// less than 60, F
//
// Read a student's scores,
// output record: scores + numeric average + assigned letter grade
//
// Use a struct to contain student record.
struct StudentRecord
{
int studentNumber;
double quiz1;
double quiz2;
double midterm;
double final;
double average;
char grade;
};
//prompts for input for one student, sets the
//structure variable members.
void input(StudentRecord& student);
//calculates the numeric average and letter grade.
void computeGrade(StudentRecord& student);
//outputs the student record.
void output(const StudentRecord student);
int main()
{
StudentRecord student[CLASS_SIZE];
for(int i = 0; i < CLASS_SIZE; i++)
input(student[i]);
// Enclosing block fixes VC++ "for" loop control defined outside loop
{ for(int i = 0; i < CLASS_SIZE; i++)
{
computeGrade(student[i]);
output(student[i]);
cout << endl;
}
}
return 0;
}
void input(StudentRecord &student)
{
cout << "enter the student number: ";
cin >> student.studentNumber;
cout << student.studentNumber << endl;
cout << "enter two 10 point quizes" << endl;
cin >> student.quiz1 >> student.quiz2;
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
cout << student.quiz1 << " " << student.quiz2 << endl;
cout << "enter the midterm and final exam grades."
<< "These are 100 point testsn";
cin >> student.midterm >> student.final;
cout << student.midterm << " " << student.final
<< endl << endl;
}
void computeGrade(StudentRecord& student)
{
// Of grade, final counts 50%, midterm 25%, quizes25%
double quizAvg= (student.quiz1 + student.quiz2)/2.0;
double quizAvgNormalized = quizAvg * 10;
student.average = student.final * 0.5 +
student.midterm * 0.25 +
quizAvgNormalized * 0.25;
char letterGrade[]= "FFFFFFDCBAA";
int index = static_cast<int>(student.average/10);
if(index < 0 || 10 <= index)
{
cout << "Bad numeric grade encountered: "
<< student.average << endl
<< " Aborting.n";
abort();
}
student.grade = letterGrade[index];
}
void output(const StudentRecord student)
{
cout << "The record for student number: "
<< student.studentNumber << endl
<< "The quiz grades are: "
<< student.quiz1 << " " << student.quiz2
<< endl
<< "The midterm and exam grades are: "
<< student.midterm << " " << student.final
<< endl
<< "The numeric average is: " << student.average
<< endl
<< "and the letter grade assigned is "
<< student.grade
<< endl;
}
Data for the test run:
1 7 10 90 95
2 9 8 90 80
3 7 8 70 80
4 5 8 50 70
5 4 0 40 35
Command line command to execute the text run:
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
ch6prg1 < data
Output:
enter the student number: 1
enter two 10 point quizes
7 10
enter the midterm and final exam grades. These are 100 point tests
90 95
enter the student number: 2
enter two 10 point quizes
9 8
enter the midterm and final exam grades. These are 100 point tests
90 80
enter the student number: 3
enter two 10 point quizes
7 8
enter the midterm and final exam grades. These are 100 point tests
70 80
enter the student number: 4
enter two 10 point quizes
5 8
enter the midterm and final exam grades. These are 100 point tests
50 70
enter the student number: 5
enter two 10 point quizes
4 0
enter the midterm and final exam grades. These are 100 point tests
40 35
The record for student number: 1
The quiz grades are: 7 10
The midterm and exam grades are: 90 95
The numeric average is: 91.25
and the letter grade assigned is A
The record for student number: 2
The quiz grades are: 9 8
The midterm and exam grades are: 90 80
The numeric average is: 83.75
and the letter grade assigned is B
The record for student number: 3
The quiz grades are: 7 8
The midterm and exam grades are: 70 80
The numeric average is: 76.25
and the letter grade assigned is C
The record for student number: 4
The quiz grades are: 5 8
The midterm and exam grades are: 50 70
The numeric average is: 63.75
and the letter grade assigned is D
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
The record for student number: 5
The quiz grades are: 4 0
The midterm and exam grades are: 40 35
The numeric average is: 32.5
and the letter grade assigned is F
*/
2. CounterType
An object of CounterType is used to count things, so it records a count that is a nonnegative
integer number. It has mutators to increment by 1 and decrement by 1, but no member allows the
counter value to go negative.
There is an accessor that returns the count value, and a display function that displays the count
value on the screen.
Apropos of confusing error messages, this one is worth comment. In compiling the code for this
problem, the following warning message was generated from VC++6.0 on the last line of the
following code fragment:
warning: integral size mismatch in argument; conversion supplied
cout << "starting at counter value "
<< localCounter.currentCount
<< "and decrementing "
<< MAX << " times only decrements to zero.nn";
If the error message had been on the offending line, it would have been trivial to see the missing
parentheses on the second line of this code fragment. Warn the students that the error message
may be given several lines after the offending bit of code.
//Ch6prg2.cpp
//CounterType
//
// The class keeps a non-negative integer value.
// It has 2 mutators one increments by 1 and
// the other decrements by 1.
// No member function is allowed to drive the value of the counter
// to become negative. (How to do this is not specified.)
// It has an accessor that returns the count value,
// and a display member that write the current count value
// to the screen.
#include <iostream>
using namespace std;
const int MAX = 20;
class CounterType
{
public:
void InitializeCounter();
void increment();
//ignore request to decrement if count is zero
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
void decrement();
int currentCount();
void display();
private:
int count;
};
int main()
{
CounterType localCounter;
localCounter.InitializeCounter();
{
for(int i = 1; i < MAX; i++)
if(i%3 == 0) // true when i is divisible by 3
localCounter.increment();
}
cout << "There are " << localCounter.currentCount()
<< " numbers between 1 and " << MAX << " that are divisible by 3.nn";
cout << "Starting at counter value "
<< localCounter.currentCount(
<< " and decrementing "
<< MAX << " times only decrements to zero.nn";
{
for(int i = 1; i < MAX; i++)
{
localCounter.display();
cout << " ";
localCounter.decrement();
}
}
cout << endl << endl;
return 0;
}
void CounterType::InitializeCounter()
{
count = 0;
}
void CounterType::increment()
{
count++;
}
void CounterType::decrement()
{
if(count > 0) count--;
}
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
void CounterType::display()
{
cout << count;
}
int CounterType::currentCount()
{
return count;
}
A run gives this output:
There are 6 numbers between
1 and 20 that are divisible by 3.
Starting at counter value 6 and decrementing 20
times only decrements to zero.
6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0
3. A Point class
A point in the plane requires two coordinates. We could choose from many coordinate systems.
The two that are most familiar are rectangular and polar. We choose rectangular coordinates (two
double values representing distances from the point in question to perpendicular coordinates).
Conversion the internal representation of this class from rectangular to polar coordinates
should be an excellent problem for students who are reasonably prepared.
These members should be implemented:
a) a member function, set, to set the private data after creation
b) a member function to move the point a vertical distance and a horizontal distance
specified by the first and second arguments.
c) a member function that rotates the point 90 degrees clockwise about the origin.
d) two const inspector functions to retrieve the current coordinates of the point.
Document the member functions.
Test with several points exercise member functions.
//Ch6prg3.cpp
#include <iostream>
using namespace std;
// Point
// The members should implement
// a)a member function, set, to set the private data after creation
// b)a member function to move the point a vertical distance and a
// horizontal distance specified by the first and second arguments.
// c)a member function that rotates the point 90 degrees clockwise
// about the origin.
// d)two const inspector functions to retrieve the current coordinates
// of the point.
// Document the member functions.
// Test with several points exercise member functions.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
class Point
{
public:
//set: set x to first, y to second
void set(int first, int second);
//move point horizontally by distance first
//move vertically by distance second
void move(int first, int second);
//rotate point 90 degrees clockwise
void rotate();
// returns the first coordinate of the point
double first();
// returns the second coordinate of the point
double second();
private:
double x;
double y;
};
double Point::first()
{
return x;
}
double Point::second()
{
return y;
}
void Point::set(int first, int second)
{
x = first;
y = second;
}
void Point::move(int first, int second)
{
x = x + first;
y = y + second;
}
void Point::rotate()
{
double tmp = x;
x = -y;
y = tmp;
}
int main()
{
Point A, B, C;
A.set(1,2);
cout << A.first() << ", " << A.second() << endl;
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
B.set(2,3);
cout << B.first() << ", " << B.second() << endl;
B.move(1,1);
cout << B.first() << ", " << B.second() << endl;
C.set(5, -4);
cout << C.first() << ", " << C.second() << endl;
cout << "Move C by -5 horizontally and 4 vertically. " << endl;
C.move(-5, 4);
cout << C.first() << ", " << C.second() << endl;
return 0;
}
In this execution of the program: We start with (1,2). This point is rotated 90 degrees, four times,
getting back to the original point. The point (3,4) is set and moved by (1,1), that is, one up, one
right). A second point, (5,-4) is set and moved by (-5,4) one left, on down. Then we move it back
to the origin, (0,0). The output from this run is:
1, 2
-2, 1
-1, -2
2, -1
1, 2
-2, 1
2, 3
3, 4
5, -4
Move C by -5 horizontally and 4 vertically.
0, 0
4. A Gas Pump Simulation
The model should have member functions that
a) display the amount dispensed
b) display the amount charged for the amount dispensed
c) display the cost per gallon
d) reset amount dispensed and amount charged to 0 prior to dispensing
e) dispense fuel. Once started the gas pump continues to dispense fuel, continually keeping
track of both amount of money charged and amount of fuel dispensed until stopped.
f) a control to stop dispensing.
The implementation was carried out as follows:
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
1) Implement a class definition that models of the behavior of the gas pump.
2) Write implementations of the member functions.
3) Decide whether there are other data the pump must keep track of that the user should not
have access to.
Parts a) b) c) d) are straightforward to implement. Part e), the pumping operation is a little tricky.
Once I realized that the valve on the nozzle must be held to continue to dispense gas, I decided to
model that behavior by repeatedly pressing <CR> is an easy step. Tweaking the appearance and
behavior detail is all that was left. The tweaking was not trivial.
There are notes in the GasPump class definition that are addressed to the instructor. These
concern members that should be declared static or should have been members of a manager class
that is a friend of this class. The student is not likely to understand these notes. I suggest that you
delete these remarks if you give this solution to the student.
#include <iostream>
using namespace std;
class GasPump
{
public:
void initialize(); // set charges, amount dispensed, and
//gasInMainTank to 0.
void reset(); // set charges and amount dispensed to 0;
void displayCostPerGallon();
//If there is only one grade, of gasoline, this should be a static
//member of GasPump, since it would then apply to all instances of
//GasPump. If there are several grades, then this and costPerGallon
//should be ordinary members.
void displayGasNCharges();
// Dispense member continually updates display of new amount and
// new charges
void dispense();
void stop(); // If called, stops dispensing operation.
// My implementation never used this.
private:
double gasDispensed;
double charge;
public:
//Perhaps these functions should be static members of this class.
//See the earlier comment about this.
void setPricePerGallon(double newPrice);
void buyFromJobber(double quantity);
void displayAmountInMainTank();
private:
//These variables should be static members, since
//they are associated with all class instances.
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
double gasInMainTank;
double costPerGallon;
};
void GasPump::displayAmountInMainTank()
{
cout << gasInMainTank;
}
void GasPump::setPricePerGallon(double newPrice)
{
costPerGallon = newPrice;
}
void GasPump::buyFromJobber(double quantityBought)
{
gasInMainTank += quantityBought;
}
void GasPump::initialize()
{
gasDispensed = 0;
charge = 0;
gasInMainTank = 0;
}
void GasPump::reset()
{
gasDispensed = 0;
charge = 0;
}
void GasPump::displayCostPerGallon()
{
cout << costPerGallon;
}
void GasPump::displayGasNCharges()
{
cout << "gallons: " << gasDispensed
<< " $" << charge << endl;
}
void GasPump::dispense()
{
char quit;
system("cls"); // Windows clear screen
//system("clear"); // Unix/Linux
cout << "nnDISPENSING FUELn";
displayGasNCharges();
cout << "nPress <CR> to dispense in 0.1 gallon increments. "
<< "nPress q or Q <CR>to terminate dispensing.n";
while(gasInMainTank > 0)
{
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
quit = cin.get();
if (quit == 'q' || quit == 'Q')
break;
charge += 0.1 * costPerGallon;
gasDispensed += 0.1;
gasInMainTank -= 0.1;
system("cls"); // Windows clear screen
//system("clear"); // Unix/Linux
cout << "nnDISPENSING FUELn";
displayGasNCharges();
cout << "nPress <CR> to dispense in 0.1 gallon increments. "
<< "nPress q or Q <CR>to terminate dispensing.n";
}
if(0 == gasInMainTank)
cout << "Dispensing ceased because main tank is empty.n";
}
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
GasPump pump;
char ans;
cout << "Gas Pump Modeling Programn";
pump.initialize();
pump.setPricePerGallon(1.50);
pump.buyFromJobber(25);
cout << "Amount of gasoline in main tank is: ";
pump.displayAmountInMainTank();
cout << endl;
cout << "Gasoline price is $";
pump.displayCostPerGallon();
cout << " per gallon.n";
pump.displayGasNCharges();
cout << "Press Y/y <CR> to run the dispensing model,"
<< " anything else quits. n";
cin >> ans;
if( !('Y' == ans || 'y' == ans) )
return 0;
system("cls"); // Windows
//system("clear"); // Unix/Linux
cout << "nWelcome Customer #1n";
cout << "Press Y/y <CR> to start dispensing Fuel,”
<< “ other quits n";
cin >> ans;
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
if('Y'==ans || 'y' == ans)
{
ans = cin.get(); // eat <cr>
pump.dispense();
}
cout << "Thank you. Your charges are:n" ;
pump.displayGasNCharges();
cout << endl;
cout << "nnAmount of gasoline remaining in main tank is: ";
pump.displayAmountInMainTank();
cout << " gallonsn";
cout << "nnWelcome Customer #2n";
pump.displayGasNCharges();
cout << "Press Y/y <CR> to start dispensing Fuel,"
<< " anything else quits dispensing. n";
cin >> ans;
if('Y'==ans || 'y' == ans)
{
pump.reset(); // zero old charges
ans = cin.get(); // eat <cr>
pump.dispense();
}
cout << "Thank you. Your charges are:n" ;
pump.displayGasNCharges();
cout << endl;
cout << "nnAmount of gasoline remaining in main tank is: ";
pump.displayAmountInMainTank();
cout << " gallonsn";
return 0;
}
5. Fraction
Define a class for a type called Fraction. This class is used to represent a ratio of two integers.
Include mutator functions that allow the user to set the numerator and the denominator. Also
include a member function that returns the value of numerator / denominator as a double. Include
an additional member function that outputs the value of the fraction reduced to lowest terms, e.g.
instead of outputting 20/60 the method should output 1/3. This will require finding the greatest
common divisor for the numerator and denominator, and then dividing both by that number.
Embed your class in a test program.
//fraction.cpp
//This program defines a class for fractions, which stores a numerator
// and denominator. A member functions allows for retrieval of the
// fraction as a double and another outputs the value in lowest
// terms.
//The greatest common divisor is found to reduce the fraction.
// In this case we use a brute-force method to find the gcd, but
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
// a more efficient solution such as euclid's method could also be
// used.
#include <iostream>
#include <cstdlib>
using namespace std;
class Fraction
{
public:
double getDouble();
void outputReducedFraction();
void setNumerator(int n);
void setDenominator(int d);
private:
int numerator;
int denominator;
int gcd(); // Finds greatest common divisor of numerator
// and denominator
};
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
// ======================
// Fraction::getDouble
// Returns the fraction's value as a double
// ======================
double Fraction::getDouble()
{
return (static_cast<double>(numerator) / denominator);
}
// ======================
// Fraction::outputReducedFraction
// Reduces the fraction and outputs it to the console.
// ======================
void Fraction::outputReducedFraction()
{
int g;
g = gcd();
cout << numerator / g << " / " << denominator / g << endl;
return;
}
// ======================
// Fraction::setNumerator
// Mutator to change the numerator
// ======================
void Fraction::setNumerator(int n)
{
numerator = n;
}
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
// ======================
// Fraction::setDenominator
// Mutator to change the denominator
// ======================
void Fraction::setDenominator(int d)
{
denominator = d;
}
// ======================
// Fraction::gcd
// Finds greatest common divisor of numerator and denominator
// by brute force (start at larger of two, work way down to 1)
// ======================
int Fraction::gcd()
{
int g; // candidate for gcd, start at the smaller of the
// numerator and denominator
if (numerator > denominator)
{
g = denominator;
}
else
{
g = numerator;
}
// Work down to 1, testing to see if both numerator and denominator
// can be divided by g. If so, return it.
while (g>1)
{
if (((numerator % g)==0) && ((denominator % g)==0))
return g;
g--;
}
return 1;
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Some test fractions
Fraction f1, f2;
f1.setNumerator(4);
f1.setDenominator(2);
cout << f1.getDouble() << endl;
f1.outputReducedFraction();
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
cout << endl;
f2.setNumerator(20);
f2.setDenominator(60);
cout << f2.getDouble() << endl;
f2.outputReducedFraction();
cout << endl;
}
6. Odometer
Define a class called Odometer that will be used to track fuel and mileage for an automotive
vehicle. The class should have member variables to track the miles driven and the fuel efficiency
of the vehicle in miles per gallon. Include a mutator function to reset the odometer to zero miles,
a mutator function to set the fuel efficiency, a mutator function that accepts miles driven for a trip
and adds it to the odometer’s total, and an accessor method that returns the number of gallons of
gasoline that the vehicle has consumed since the odometer was last reset.
Use your class with a test program that creates several trips with different fuel efficiencies. You
should decide which variables should be public, if any.
//odometer.cpp
//This program defines an Odometer class to track fuel and mileage.
// It stores the miles driven and fuel efficient and includes
// a function to calculate the number of gallons of gasoline consumed.
#include <iostream>
#include <cstdlib>
using namespace std;
class Odometer
{
public:
void setFuelEfficiency(double newEfficiency);
void reset();
void logMiles(int additionalMiles);
double gasConsumed();
private:
int miles;
double fuel_efficiency;
};
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
// ======================
// Odometer::setFuelEfficiency
// Sets the fuel efficiency in miles per gallon.
// ======================
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
void Odometer::setFuelEfficiency(double newEfficiency)
{
fuel_efficiency = newEfficiency;
}
// ======================
// Odometer::reset
// Resets the odometer reading
// ======================
void Odometer::reset()
{
miles = 0;
}
// ======================
// Odometer::addMiles
// Log additional miles to the odometer.
// ======================
void Odometer::logMiles(int additionalMiles)
{
miles += additionalMiles;
}
// ======================
// Odometer::gasConsumed
// Calculates the gallons of gas consumed on the trip.
// ======================
double Odometer::gasConsumed()
{
return (miles / fuel_efficiency);
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Two test trips
Odometer trip1, trip2;
void setFuelEfficiency(double newEfficiency);
void reset();
void logMiles(int additionalMiles);
double gasConsumed();
trip1.reset();
trip1.setFuelEfficiency(45);
trip1.logMiles(100);
cout << "For your fuel-efficient small car:" << endl;
cout << "After 100 miles, " << trip1.gasConsumed() <<
" gallons used." << endl;
trip1.logMiles(50);
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
cout << "After another 50 miles, " << trip1.gasConsumed() <<
" gallons used." << endl;
cout << endl;
trip2.reset();
trip2.setFuelEfficiency(13);
trip2.logMiles(100);
cout << "For your gas guzzler:" << endl;
cout << "After 100 miles, " << trip2.gasConsumed() <<
" gallons used." << endl;
trip2.logMiles(50);
cout << "After another 50 miles, " << trip2.gasConsumed() <<
" gallons used." << endl;
}
7. Pizza
Define a class called Pizza that has member variables to track the type of pizza (either deep
dish, hand tossed, or pan) along with the size (either small, medium, or large) and the number of
pepperoni or cheese toppings. You can use constants to represent the type and size. Include
mutator and accessor functions for your class. Create a void function, outputDescription( ),
that outputs a textual description of the pizza object. Also include a function, computePrice( ),
that computes the cost of the pizza and returns it as a double according to the rules:
Small pizza = $10 + $2 per topping
Medium pizza = $14 + $2 per topping
Large pizza = $17 + $2 per topping
Write a suitable test program that creates and outputs a description and price of various pizza
objects.
Notes: You may wish to point out that this could be better organized using inheritance and
classes for each type of pizza.
// pizza.h
//
// Interface file for the Pizza class.
const int SMALL = 0;
const int MEDIUM = 1;
const int LARGE = 2;
const int DEEPDISH = 0;
const int HANDTOSSED = 1;
const int PAN = 2;
class Pizza
{
public:
Pizza();
~Pizza() {};
int getPepperoniToppings();
void setPepperoniToppings(int numPepperoni);
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
int getCheeseToppings();
void setCheeseToppings(int numCheese);
int getSize();
void setSize(int newSize);
int getType();
void setType(int newType);
void outputDescription();
double computePrice();
private:
int size, type, pepperoniToppings, cheeseToppings;
};
// pizza.cpp
//
// This program implements the Pizza class and creates several
// pizza objects to test it out.
#include <iostream>
#include "pizza.h"
using namespace std;
//========================
// Pizza
// The constructor sets the default pizza
// to a small, deep dish, with only cheese.
//========================
Pizza::Pizza()
{
size = SMALL;
type = DEEPDISH;
pepperoniToppings = 0;
cheeseToppings = 1;
}
//==================================
// Accessors and Mutators Follow
//==================================
// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------
int Pizza::getPepperoniToppings()
{
return pepperoniToppings;
}
void Pizza::setPepperoniToppings(int numPepperoni)
{
pepperoniToppings = numPepperoni;
}
int Pizza::getCheeseToppings()
{
return cheeseToppings;
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
}
void Pizza::setCheeseToppings(int numCheese)
{
cheeseToppings = numCheese;
}
int Pizza::getSize()
{
return size;
}
void Pizza::setSize(int newSize)
{
size = newSize;
}
int Pizza::getType()
{
return size;
}
void Pizza::setType(int newType)
{
type = newType;
}
//==================================
// outputDescription
// Prints a textual description of the contents of the pizza.
//==================================
void Pizza::outputDescription()
{
cout << "This pizza is: ";
switch (size)
{
case SMALL: cout << "Small, ";
break;
case MEDIUM: cout << "Medium, ";
break;
case LARGE: cout << "Large, ";
break;
default: cout << "Unknown size, ";
}
switch (type)
{
case DEEPDISH: cout << "Deep dish, ";
break;
case HANDTOSSED: cout << "Hand tossed, ";
break;
case PAN: cout << "Pan, ";
break;
default: cout << "Uknown type, ";
}
cout << "with " << pepperoniToppings << " pepperoni toppings " <<
"and " << cheeseToppings << " cheese toppings." << endl;
}
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
//==================================
// computePrice
// Returns:
// Price of a pizza using the formula:
// Small = $10 + $2 per topping
// Medium = $14 + $2 per topping
// Large = $17 + $2 per topping
//==================================
double Pizza::computePrice()
{
double price = 0;
switch (size)
{
case SMALL: price = 10; break;
case MEDIUM: price = 14; break;
case LARGE: price = 17; break;
default: cout << "Error, invalid size." << endl;
return -1;
}
price += (pepperoniToppings + cheeseToppings) * 2;
return price;
}
// --------------------------------
// --------- END USER CODE --------
// --------------------------------
// ======================
// main function
// ======================
int main()
{
// Variable declarations
Pizza cheesy;
Pizza pepperoni;
cheesy.setCheeseToppings(3);
cheesy.setType(HANDTOSSED);
cheesy.outputDescription();
cout << "Price of cheesy: " << cheesy.computePrice() << endl;
pepperoni.setSize(LARGE);
pepperoni.setPepperoniToppings(2);
pepperoni.setType(PAN);
pepperoni.outputDescription();
cout << "Price of pepperoni : " << pepperoni.computePrice() << endl;
cout << endl;
}
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
8. Money
Define a class named Money that stores a monetary amount. The class should have two private
integer variables, one to store the number of dollars and another to store the number of cents.
Add accessor and mutator functions to read and set both member variables. Add another
function that returns the monetary amount as a double. Write a program that tests all of your
functions with at least two different Money objects.
#include <iostream>
using namespace std;
class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
int dollars;
int cents;
};
int Money::getDollars()
{
return dollars;
}
int Money::getCents()
{
return cents;
}
void Money::setDollars(int d)
{
dollars = d;
}
void Money::setCents(int c)
{
cents = c;
}
double Money::getAmount()
{
return static_cast<double>(dollars) +
static_cast<double>(cents) / 100;
}
int main( )
{
Money m1, m2;
m1.setDollars(20);
m1.setCents(35);
m2.setDollars(0);
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
m2.setCents(98);
cout << m1.getDollars() << "." << m1.getCents() << endl;
cout << m1.getAmount() << endl;
cout << m2.getAmount() << endl;
cout << "Changing m1's dollars to 50" << endl;
m1.setDollars(50);
cout << m1.getAmount() << endl;
cout << "Enter a character to exit." << endl;
char wait;
cin >> wait;
return 0;
}
9. Money Data Hiding
Do Programming Project 6.8 except remove the two private integer variables and in their place
use a single variable of type double to store the monetary value. The rest of the functions
should have the same headers. For several functions this will require code to convert from an
integer format to appropriately modify the double. For example, if the monetary amount stored
in the double is 4.55 (representing $4.55) then if the function to set the dollar amount is invoked
with the value 13, then the double should be changed to 13.55. While this will take some work,
the code in your test program from Programming Project 6.8 should still work without requiring
any changes. This is the benefit of encapsulating the member variables.
#include <iostream>
using namespace std;
class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
//int dollars, cents; // In OLD version
double amount;
};
int Money::getDollars()
{
// return dollars
return static_cast<int>(amount);
}
int Money::getCents()
{
//return cents;
int val = static_cast<int>(amount * 100);
if (val > 0)
return val % 100;
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
// The following logic handles negative amounts
else if ((val < 0) && (val > -1))
// Negative cents (no neg dollars)
return val % 100;
else
// No neg cents (neg dollars)
return -1 * (val % 100);
}
void Money::setDollars(int d)
{
int pennies = getCents(); // Current cents
amount = static_cast<double>(d) + (pennies / 100.0);
//dollars = d;
}
void Money::setCents(int c)
{
amount = static_cast<double>(getDollars()) +
(c / 100.0);
//cents = c;
}
double Money::getAmount()
{
//return static_cast<double>(dollars) +
// static_cast<double>(cents) / 100;
return amount;
}
// This main function is identical to the PP 6.8
int main( )
{
Money m1, m2;
m1.setDollars(20);
m1.setCents(35);
m2.setDollars(0);
m2.setCents(98);
cout << m1.getDollars() << "." << m1.getCents() << endl;
cout << m1.getAmount() << endl;
cout << m2.getAmount() << endl;
cout << "Changing m1's dollars to 50" << endl;
m1.setDollars(50);
cout << m1.getAmount() << endl;
cout << "Enter a character to exit." << endl;
char wait;
cin >> wait;
return 0;
}
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual
Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.
10. Temperature Class
Create a Temperature class that internally stores a temperature in degrees Kelvin. However,
create functions named setTempKelvin, setTempFahrenheit, and setTempCelsius
that takes an input temperature in the specified temperature scale, converts the temperature to
Kelvin, and stores that temperature in the class member variable. Also create functions that
return the stored temperature in degrees Kelvin, Fahrenheit, or Celsius. Write a main function to
test your class. Use the equations below to convert between the three temperature scales.
Kelvin = Celsius + 273.15
Celsius = (5/9) X (Fahrenheit - 32)
#include <iostream>
using namespace std;
class Temperature
{
public:
void setTempKelvin(double temp);
void setTempFahrenheit(double temp);
void setTempCelsius(double temp);
double getTempKelvin();
double getTempFahrenheit();
double getTempCelsius();
private:
double kelvin; // Internally store temp in kelvin
};
void Temperature::setTempKelvin(double temp)
{
kelvin = temp;
}
void Temperature::setTempFahrenheit(double temp)
{
kelvin = (5.0 * (temp - 32) / 9) + 273.15;
}
void Temperature::setTempCelsius(double temp)
{
kelvin = temp + 273.15;
}
double Temperature::getTempKelvin()
{
return kelvin;
}
double Temperature::getTempCelsius()
{
return kelvin - 273.15;
}
double Temperature::getTempFahrenheit()
{
Exploring the Variety of Random
Documents with Different Content
"Good-morning, Mr. Rimmon. I s'pose ye heerd what th' judge sed
las' evenin' thet I'm to carry th' mail arter this. I hev resigned the
Tree office, so it's all regular. Seein' I'm new to th' bizness, I thought
mebbe ye wouldn't object to lettin' me start a leetle arly th' fust
time."
"I shall object, most decidedly, Mr. Shag."
"Hev yit yer own way, Mr. Rimmon, though ye'll find I ain't a boy to
be run over. Ye'll let me hev it at six sharp, or thar'll be war in th'
United States camp."
To this the postmaster made no reply, while one and all waited the
outcome of this trying scene.
In the midst of the fearful ordeal the sun rose above the crest of the
distant mountains, and then a murmur ran along the expectant
crowd.
"It's six o'clock!" cried Sheriff Brady, consulting his watch. "The time
is up, Mrs. Lewis, and the boy has not come, as I knew he wouldn't.
I have kept my word, and you cannot expect any more."
"It's six!" exclaimed Dan Shag, moving uneasily in his saddle. "Hand
over thet mail bag, Mr. Rimmon, fer ye can't hol' it enny longer."
The postmaster cast a last, anxious gaze down the road before he
replied, and then a cry of great relief left his lips.
"He is coming!"
Eagerly the spectators looked down the road, and a murmur of joy
arose on the air, as they saw the figure of a horse galloping rapidly
toward the town. But the look of relief on the faces of all turned to
one of dread expectancy, as they discovered that the creature was
riderless!
It was Jack, the postboy's favorite steed, his sides covered with
foam, and his breath coming in quick, short gasps, as he sped like
the wind toward his home, but Little Snap was not on his back!
CHAPTER XVI.
A LONELY NIGHT RIDE.
During this long, anxious night how has it fared with Little Snap? Is
the return of Jack without him a good or an evil omen?
Let us see.
His most direct course to Volney was by the post road to Greenbrier,
after which he must take a more southerly direction by following the
left bank of the Little Kanawha to the Blue Stone River. From this
junction he was to ride ten miles within sound of this stream, when
he must leave the river road for one leading over the hills to the
east.
Though there was no moon, the night was made pleasant by a
myriad of stars in the mellow autumn sky, so he rode on with a
hopeful heart that he should have no trouble in finding his way.
Not a light was to be seen at Daring's Diamond, but quite
unexpectedly a dim blaze shone from Hollow Tree, though he had
not supposed the postmaster had had time to get home from Six
Roads.
But every moment was of value to him, so he dashed past the lonely
place without slackening his pace, until he reached the homely
village of Greenbrier.
Even then he was rushing on at the same headlong pace he had
followed since leaving home, when suddenly a familiar voice
arrested his flight.
"What in the name of George Washington are you riding like that for,
Dix Lewis?"
The speaker was a Mr. Renders, whom Little Snap had always
considered friendly to him, so he reined in Fairy and quickly
explained the object of his long ride.
"I am afraid it will prove a wild-goose ride, Dix, but I wish you
success. Say, I'll tell you how I can help you. I have a brother living
at the corner of the Blue Stone and Mountain roads, and he has a
horse you can get to finish your journey with, and leave yours there
to rest till you come back. I think it is about ten miles from my
brother's to Volney. A shift of horses will come in mighty handy
about that time. Let me write a line to Joe, which will make your
chances doubly sure."
Mr. Renders wasn't long in carrying out his intentions, and, thanking
him for his kindness, the postboy again urged Fairy on, the trusty
Jack keeping beside his mate without attention from his master.
The Little Kanawha road was an extremely lonely one, but being
nearly level, Little Snap sped on with unabated speed.
Thus he had swung around a sharp bend in the highway, when he
was surprised by a beseeching voice calling out:
"Hold up, mister, a minute! Don't be scart, for I ain't a highwayman,
but I want a ride!"
The speaker rose so nearly from the middle of the road that Jack
had to shy in order to avoid running over him.
"I can't go no farther, mister! so please have pity on me."
Owing to the thick growth by the roadside, it was too dark for the
boy rider to distinguish the features of the stranger. He was a burly
framed man, and seemed to be shabbily dressed. He carried a short,
heavy stick, whether for a cane or a weapon of defense Little Snap
had no time to consider.
"You have a spare horse," continued the other, without giving the
postboy opportunity to reply to him. "Let me ride him, and you'll do
the greatest favor of your life. It is a case of got to with me, or I
would not ask it. I am on my way to see a dying mother, and I have
walked till I can't get one foot ahead of the other any longer."
He had caught hold of Jack's rein, for Little Snap had put a bridle on
the horse before starting, and he was in the act of climbing into the
saddle.
"Hold on, sir!" exclaimed Dix Lewis, sharply. "I do not doubt your
honesty——"
"It's a case of must, mister! Let me ride him if for only a mile. He's
doing you no good."
"I have got a long journey ahead—so long that I must have him
fresh to help me get there. I am sorry to refuse you."
"It's such a small thing I ask of you, and you can do it just as well as
not. Think if your mother was dying and you were thirty miles from
her, and you should ask a man to let you ride a spare horse he had
to see her. I will give you a hundred dollars if you will let me ride ten
miles."
Uttered in a pleading, earnest tone, the words touched the postboy's
heart.
"Where do you wish to go?"
"To the town of Volney. If you are any acquainted there you may
know Marion Calvert. He is my cousin. My name is Atwin, and I live
in Frankfort."
"You know Marion Calvert? I am going to see him!"
"You don't say so! Perhaps you are a relation of his?"
"No, sir. I am going to see him on business. Every moment is
precious to me, too, for I must get back before morning."
"I am sorry to have bothered you, but it was a case of necessity. You
are going to let me ride?"
Little Snap was never so puzzled in his life. While not wishing to
refuse the man, he still knew it would jeopardize his chances of
getting back to Six Roads in season.
While he hesitated a moment, the stranger moved nearer Jack, and
gathering himself to spring into the seat, said:
"I shall never—whoa! Stand still, you brute!"
Jack had begun to step backward, and flinging up his head, broke
the man's hold from the bridle.
Then uttering a snort, Jack darted forward to Little Snap's side.
"What sort of a confounded hoss have you got here?" cried the
unknown, again seizing the bridle, this time leaping nimbly into the
saddle.
"What is the trouble, Jack, old boy?" asked his master, wondering at
the creature's singular and unusual action.
No sooner had the stranger gained the seat than the horse sprang
abruptly to one side, and rearing into the air, sent the man flying
heels over head into the bushes by the roadside.
All of this was done so suddenly that Little Snap had not found time
to express his amazement.
As if impelled by a newborn fear, Jack bounded up the road, with a
whinny of terror.
"Hi, there! help—quick—he'll get away from me!" cried the man,
staggering to his feet and bursting through the bushes into the road.
Though startled by this unexpected turn in affairs, the postboy had
presence of mind enough to see that the stranger was no longer a
supplicant for favors, but that a fierce determination to gain his ends
was apparent on his features and in his voice.
He started to catch hold of Fairy's bridle, but with a snort of defiance
the creature threw back her head, and Little Snap, reading the
other's purpose, touched her smartly with the spur.
At that moment the tramp of feet came from the growth, and the
burly figures of three or four men sprang into sight.
CHAPTER XVII.
LITTLE SNAP'S DISAPPOINTMENT.
"He's getting away!" shouted the man who had hailed the postboy.
"Come on, you lubbers!"
If Little Snap had been taken off his guard at first, he was wide
awake enough now, and giving Fairy an encouraging cry, he was
borne swiftly away by the fleet-footed mare.
Glancing back once more, he saw the four men in pursuit of him, but
as long as they were on foot, he had but little to fear from them.
With their hoarse shouts ringing in his ears, he sped around a curve
in the road and out of their sight.
After he had gone a couple of miles, finding that he was not likely to
be troubled by their pursuit, he slackened Fairy's speed, and
improved his first opportunity to bend over and pat Jack's head close
beside him, saying:
"Noble boy, you knew more than your master that time. I wonder
where I should be now if you hadn't read that fellow's intentions
better than I did? I wasn't quite satisfied with him, but his story did
throw me off my guard. I have got to keep my eyes open sharper
than that."
Talking thus, half to his animal friends and half to himself, he rode
swiftly on toward Volney, the soft, clayey soil muffling the hoof
strokes of his horses so that they gave back no sound, his advance
scarcely breaking in upon the silence of the night.
Soon after his escape from the waylayers, whom he judged the men
to be, he shifted upon Jack, giving Fairy a rest.
To his joy he at last came to what he was confident was the corner
of the Blue Stone and Mountain roads spoken of by Mr. Renders.
If he had had any lingering doubts about this, they were driven
away at sight of a farmhouse standing back a short distance from
the latter highway and nearly concealed by a clump of trees, and
which he knew must be the house of Mr. Renders' brother.
An unnatural stillness seemed to hang over the place, and at first he
was inclined to ignore Mr. Renders' advice and keep on. But he knew
only too well that Jack and Fairy needed all the rest they could get
before completing their long journey.
Accordingly, he advanced boldly to the door, and seizing the heavy
brass knocker, he raised a noise that must have aroused every
inmate of the house.
Heads quickly began to appear from the windows, until he imagined
he had awakened a house full of people.
"Who's there, and what is wanted at this unseemly hour?"
demanded a voice he felt sure belonged to the host.
Little Snap quickly explained his situation, and as he finished
speaking, handed Mr. Renders the note sent by his brother.
"Wait till I can strike a light, when I will read it, and if I think
favorable of what he says, I will be out in a moment."
Then the window was closed, while a minute later a light shone from
the apartment.
This last soon began to move about, and it was not long before the
door was opened, when Mr. Renders appeared fully dressed.
"Hope you will excuse my delay, but I didn't keep you waiting longer
than I could help. So you have come from Six Roads?"
"Yes, sir; and I have got to get back there before six o'clock this
morning, or I would never have troubled you."
"Never mind that. I have called better men than I am out of their
nests on worse nights than this. In regard to a horse, I have one
which can take you to Volney and back in one hour, though I don't
care about having you crowd him quite as hard as that, unless it is
necessary."
"I will not hurt the horse. Can you let me have him? I will pay you
well——"
"A fig for the pay! Dismount and turn your animals into that pen. I
claim a horse can rest better by having a chance to move about if he
wants to. I will feed them as soon as they have cooled off
somewhat. I will lead out my horse."
Hardly able to comprehend that he was so well favored, Little Snap
did as he was told, and by the time he had seen Fairy and Jack in
comfortable quarters, Mr. Renders had his horse ready for him to
spring into the saddle.
"He may need a little urging, but don't spare him. It is eleven miles
to Volney, and he is good for the trip and return without any more
stop than you will wish to make with Mr. Calvert. I think you will be
fortunate enough to find that gentleman at home."
Mr. Renders then described Mr. Calvert's house to him, so he would
have no difficulty in finding it, when Little Snap began the second
stage of his journey.
The road now more broken than it had been since leaving
Greenbrier, Little Snap rode on over hill and through valley, finding
the horse loaned him by Mr. Renders an exceptionally fine animal.
He had consulted his watch to find it was a quarter of two, when he
looked ahead to see what he believed to be the village of Volney.
"Almost there," he muttered. "How glad I am. Now if I find Mr.
Calvert at home I shall be soon on my return journey. That is the
house Mr. Renders described, I am sure. How still it looks around it!"
Speaking his thoughts thus aloud, Little Snap dashed into the
spacious grounds surrounding the quaint, old-fashioned dwelling he
supposed was the home of the man he had ridden so far to see.
The occupant of the house proved to be more wakeful than he had
expected, for he had barely pulled rein under the enormous willow
growing by the door before a chamber window was opened, and a
man's voice demanded.
"Who's there?"
"My name is Lewis, and I am from Union Six Roads. Does Mr. Calvert
live here?"
"That's my name, sir, though I do not recognize yours."
"I carry the mail on the Kanawha route. Of course, you remember
Dix Lewis, to whom you sub-let the line?"
"Wait a minute and I'll be down there."
Giving the finishing touches to his toilet, as he appeared, Mr. Calvert
soon opened the heavy door and stepped out into the night.
He was a man in the vicinity of forty, with a frank, good-natured
looking countenance, who seemed rather brusque in his movements
and manner of speaking.
"I hardly remember your countenance, Mr. Lewis," he said, as he
stepped forward and extended his right hand; "but that is nothing
strange, as we never met but that once. What in the name of
Congress has brought you here at this unexpected hour? But excuse
me, dismount, put your horse in the barn, and come into the house
before you begin your talk. I would call one of the negroes, but they
are so sleepy at this time of night they are no good."
"I can't stop," said Little Snap, as soon as he could find an
opportunity to speak. "I have to get back to Six Roads in season to
take the mail to the Loop to-day."
"You won't do it, all the same. But what's up?"
The postboy then made the other acquainted with all that had
happened, interrupted several times by Mr. Calvert, who finally
exclaimed:
"A bad pickle, I should say. But I am glad you have come to me. Of
course the only thing for you to do is to get out of it."
"I cannot do that with honor to myself," said Little Snap, who had
not expected this from the contractor. "It would look as if I was
really to blame for all they have said."
"Better let it look like that than to get your neck in the halter, or a
bullet through your head."
The postboy could not help showing his surprise. Was it for this he
had ridden so far, and with such high-colored hopes? He had not
dreamed of anything other than assistance from the man who was
behind him in his undertaking.
CHAPTER XVIII.
A PERILOUS UNDERTAKING.
"You will go up to Six Roads and see what can be done?" he asked,
while his hopes sank lower and lower.
"I can't. Say, tell you what I will do. I am intending to start for
Washington to-day; but when I get through there, and it won't take
me more than a week. I will come back by way of the Six Roads. I
wish I had let the plaguey route alone."
"That will be too late to help me," said Little Snap.
"I tell you, you want to get out of it as quick as you can. Let this
Shag you speak of carry the mail until I can get around."
"I am afraid you do not understand the situation, Mr. Calvert. There
is some sort of a conspiracy to rob the government, and this Dan
Shag is one of those at the bottom of it."
"Oh, nonsense! you have your suspicions and jump at conclusions. It
may be that some of them are trying to crowd you a little, seeing
you are a boy, but we all have to put up with such things. We laugh
at them when we grow older. Come into the house and have some
refreshments and a few hours' sleep before you attempt your long
journey home. Jove! you showed good grit in undertaking it."
"I undertook it in the good faith that you would stand by me in this
affair, Mr. Calvert, and though it is worth something for me to know
how you feel about it, I am disappointed to find you do not care for
the welfare of the route, for whose success or failure you are really
responsible."
"You are pretty blunt, I will say that for you. I am inclined to think
you will be a hard one for them to bluff down."
"I shall stand up for my rights, Mr. Calvert, as long as I can. Can't
you come to Six Roads before you go to Washington? They are
expecting you."
"You said Mr. Warfield still stands by you?"
"Yes, sir."
"Then, I think I can fix you all right. I will give you a note to him to
stand by you until I come to town, though I still advise you to get
out of it."
Little Snap saw that it was no use to urge him more, so he remained
silent, while Mr. Calvert hastily scribbled away on a slip of paper he
took from his pocket. When he had finished, he read:
"Volney, Va., Sept. 18.
"Mr. Jason Warfield, Union Six Roads, Va.
"Dear Sir: Stand by the bearer of this, Mr. Dix Lewis, in his
troubles as far as you think prudent, until I can see you.
Your obt. servant,
Marion Calvert."
"There, I think that will do the business. Sorry you don't feel like
coming in to rest until daylight. It's a long, lonesome ride before
you."
Thanking him, Little Snap took the piece of paper, and carefully
placing it in one of his pockets, he wheeled the horse about to start
homeward.
"Hold on!" cried Mr. Calvert, as the postboy gained the road.
Little Snap turned the horse and galloped back into the yard,
wondering and hoping.
"I wanted to say that you will no doubt see the wisdom of my advice
before you get home."
"If that is all you have to say to me farther, Mr. Calvert," said our
hero, somewhat sharply, "I will bid you good-night! My name is at
stake in this matter, and I will know the right and the wrong of it
before I am driven out."
The postboy spoke more sharply than he intended, but the other's
last words had cut like a knife. Without waiting for a reply, he
touched the horse smartly with the spurs and sped down the road at
a furious pace.
"I should know he was a Lewis if I hadn't heard his name," muttered
the mail contractor, as he watched the boyish rider out of sight. "I
ought to have known better than to have let him fool with the
business at the outset, but Rimmon said he could do it. Well, I must
get ready for my start to the capital."
His hopes crushed, so far as expecting any aid from Mr. Calvert was
concerned, Little Snap pursued his homeward journey with a gloomy
mind. Since midnight the sky had become overcast, so it was quite
dark—too dark for him to note his surroundings with any clearness.
The ride back as far as Mr. Renders' seemed shorter than he had
expected, and he found that gentleman awaiting his coming.
"You went pretty quick, but Jim don't show his journey a bit. I tell
you that horse can't be beat very easy. Pay? I don't want a red cent.
I have fed your horses, so they are all right to start. How'd you find
Calvert? He's cranky sometimes, but a fairly good sort of a fellow as
men go. Wish he might go to Congress rather than that old Warfield.
Never liked that old duffer; he's deceitful. Nothing of that kind about
Cal. Hello! Starting?"
While Mr. Renders had been running on in his sort of haphazard way,
Little Snap had put the saddle on Jack's back and sprung into the
seat.
"I wish you would take pay for the use of your horse, Mr. Renders,
but if you won't, I am a thousand times obliged to you, and I hope I
can do you a favor some time. Good-night."
"He's right after his business!" said the other to himself, as the
clatter of horses' hoofs died out in the distance. "That boy is bound
to succeed."
Riding swiftly homeward, Little Snap was saying to his dumb
companions:
"I have to fight my own battles, and this trip has been for nothing.
No; not for nothing, for I know just what to do now. You needn't
crowd on quite so hard, Jack; we have plenty of time."
Shifting from one animal to the other when he thought best, Little
Snap rode on through the night, unmindful of the gathering
stormclouds, though he kept a sharp gaze as he drew near the
lonesome spot where he had been accosted by the stranger.
Not a sound broke the deathlike silence, save the dull tramp of his
horses' feet, and with a feeling of relief he had soon left the place a
mile behind.
At Greenbrier the postboy shifted steeds, giving Jack another rest,
intending to return to him at Daring's Diamond.
No one was astir at this place yet, neither was there any sign of life
at Hollow Tree. But he hadn't gone a dozen rods beyond the Tree
before a sharp voice commanded him to stop, and he suddenly
found his way blocked with a body of armed men.
Three or four caught upon Fairy's bit with a force which dragged her
back upon her haunches, and Little Snap was nearly pulled from his
seat.
Realizing his desperate situation, the postboy dextrously slipped the
bridle from the mare's head, at the same time shouting for her to
rush on. Rallying, she made the wild attempt, and Jack, having
already cleared a way through the party, she followed upon his
heels.
Shots rang about the fleeing postboy's head, some of the bullets
flying uncomfortably near, but he fancied he was going to get away,
when he dashed furiously down the descent leading to Greenbrier
bridge.
As he came in sight of the stream with its high, precipitous banks, a
cry of dismay left his lips. Every bridge plank had been removed,
and only the stringers spanned the dark chasm of foaming waters!
Retreat cut off, with no possible chance to ford the stream, Little
Snap saw at a glance that he was rushing into a veritable deathtrap!
The cries of his pursuers rang exultantly in his ears.
CHAPTER XIX.
THE BUSHBINDERS' PLANS.
Little Snap's first impulse, as he saw the trap into which he had been
driven, was to turn at bay and meet his enemies in a hand-to-hand
struggle, as hopeless as his chances were.
But at that moment Jack had reached the bank of the stream, and
the fleeing horse, instead of checking his speed or turning aside,
sped like an arrow out over one of the bridge stringers toward the
other side!
The postboy was not far behind the gallant steed, but he had
opportunity to see the horse rush safely the length of the timber, to
reach the clear way beyond.
With a snort, as if of triumph, Jack renewed his swift flight now in
comparative safety.
The sight of this feat caused the hopes of Little Snap to rise, and he
resolved to follow the example set by his equine friend.
"On, Fairy!" he cried; "it is our only chance!"
The pursuers suddenly stopped, as they beheld with amazement the
daring deed attempted by the fugitive.
Fairy, seeming to realize the desperate part she was to act in the
startling undertaking, rushed fearlessly in the steps of her mate.
Sitting firmly in his saddle, the postboy felt himself carried out over
the dark chasm, and he caught a gleam of the foaming waters
hurling their forces madly against the rock walls of the channel. The
next instant he felt a quiver run through the frame of the faithful
steed, and he knew that she was falling!
Under the weight of her burden the mare somehow missed her
footing, her feet slipped on the treacherous way, and she tried in
vain to recover her equilibrium.
Finding that she was falling, Little Snap freed his feet from the
stirrups just as horse and rider shot headlong into the boiling river!
At that moment the pursuing party halted on the bank of the
stream, amazed witnesses of the mishap.
Little Snap was carried completely over a stringer running parallel
with the first, and, lighter than the horse, struck in the water farther
down the stream.
Fortunately, he escaped the jagged rocks of the banks, though the
fall deprived him for a time of his senses. When he came to a
realization of his situation, he found himself struggling in a mass of
débris which had clogged the river a short distance below the
crossing.
In the midst of his efforts to extricate himself, he heard a voice just
above him. Then, as he peered out from his retreat, he saw some of
his enemies coming rapidly toward the place.
"I can see him!" cried the foremost. "I knew he came down this
way."
"Give up, younker!" called another voice. "Ye mought as well, fer we
air sure to git yer."
Letting go the branch upon which he had found himself clinging,
Little Snap hoped to elude his foes by swimming down the stream.
But he found himself so entangled in the mass of floating wood
about him, that before he could get clear, the party was in the water
beside him.
A sharp struggle ensued, but at its end the postboy was dragged out
of the water by the hands of the Burrnock gang.
"Bind him, boys!" said the leader, exultantly. "That's gittin' him what
I call mighty easy. I tole yer the bridge racket would fix him."
"What do you mean by this treatment?" demanded the postboy, as
he found himself bound hands and feet.
"Keep cool an' ye'll find out quick 'nough, younker. Tote him erlong,
boys."
Little Snap looked for some trace of Fairy, but in vain.
Nothing further was said by his captors, while he was borne away
into the depths of the forest, subject to such thoughts and feelings
as may be imagined. What would they think at home of his non-
appearance when the time for his return came? Then he thought of
Jack, and wondered if the horse would keep on until he had reached
Six Roads. He was certain the steed would, and this gave him the
only hope he felt in his captivity.
At last the captors and their prisoner reached the little opening
marking the top of the bluff overhanging the cave, where Little Snap
had once sought Ab Raggles.
In the party which had effected his capture he saw Buzzard and
Hawk Burrnock, while the leader of the gang was none other than
he who had been chief spokesman in the cavern. This man the
postboy soon found was Bird Burrnock, the father of the four
brothers.
As soon as the underground room was reached, Bird Burrnock
addressed the captive as follows:
"Time is too mighty short, younker, fer us to perlaver with yer. 'Tis
true we mought hev saved a good leetle slice o' yit by knockin' ye in
th' head when we pulled ye out'n th' river. To speak th' truth, I
hoped th' river would fix yer; but seein' yit wan't likely to, we got
round in season to take enny idee o' escape ye mought hev hed out
yer head.
"We know yer air wanted mighty bad up to th' Roads, but we want
yer wuss hyur, though they air playin' inter our hands. Still, yer
mought give 'em th' slip. Yer can't us! But this ain't bizness.
"To say nothin' o' th' shabby way yer treated th' boys, we hev a
double puppose in gittin' yer inter our grips. Yit don't make enny
difference to ye wot it is, so long es 'tis so. Now we hev got yer, we
hev got a leetle proposition to make yer, on which yer future
happiness depends, es th' parson would say.
"'Tan't enny use fer me to deny, but we hev got our eye on thet mail
route, 'cos we think yit can be made a mighty payin' investment.
Shag wants to run in shacks with us, but we like yer grit well 'nough
to make a bargain with ye. Now, if ye'll 'gree to stand in with us, an'
do th' square thing, we'll not only give ye a shake in th' profits, but
we'll see thet ye don't hev enny trubble. All ye'll hev to do will be to
stop yer hoss long 'nough fer us to look th' baggage over. Mind ye,
we do th' sortin'. Further, we promise thet ye won't hev enny further
trubble at Six Roads, or ennywhere else. Is't a trade, younker?"
Little Snap was so amazed at this audacious scheme that at first he
could not find tongue to reply to Bird Burrnock.
"What if I refuse to enter into any such a contract?"
"Then our own safety demands thet we put ye where ye can't
trubble us enny more. But ye won't?"
"I'll not stand in with you!"
At this declaration the little knot of listeners started excitedly, and
Bird Burrnock, the leader, uttered a fearful oath.
"Then ye wanter die, younker?" he hissed.
"Of course I do not, sir! But I cannot lend my aid to any such
infamous scheme. Why, it's robbery of the worst sort, and you
cannot carry it on for any length of time without being caught."
"Thet's our lookout. Mebbe ye air shaky in thet direction, but I can
tell yer we air well heeled thet way. Why, th' most' influential citizens
o' th' Roads air in with us. There's th' judge, an' the colonel. Then,
too, we'll take keer o' Shag. Once more, will yer fall with th' plan, or
shall we be 'bliged to take desprit measures with yer?"
Little Snap realized that he was in the power of men who would
hesitate at nothing to carry out their unlawful purpose, and he
thought of his mother even then anxiously awaiting his return home,
and imagined the anguish she would feel upon his failure to come.
He thought of his father, so helpless to aid the others, and his
younger sister and brother, and the sorrow they would experience.
Still, with these sad reflections in his mind, and the dread
consequence if he refused to comply with the demands of his
captors plainly before him, he hesitated but a moment in his reply.
"I cannot accept your terms."
"Fetch erlong th' rope, boys," ordered Bird Burrnock, tersely. "I
reckon 'twon't take us long to change his mind."
CHAPTER XX.
A STARTLING DISCOVERY.
Buzzard Burrnock quickly entered one of the dark recesses of the
cavern, returning a moment later with a coil of rope on his arm.
"Make a loop in one end," commanded the elder Burrnock. "Be lively,
too, fer we don't want to fool with him hyur all day."
When the rope had been arranged to their satisfaction, the noose
was slipped over Little Snap's shoulders, so the cord encircled his
body under the arms.
"Drag him to th' pit!" cried the leader. "Reckon a leetle consideration
there'll take th' starch out'n him."
Buzzard Burrnock and Hawk seized hold of the postboy, one on
either side, and half dragging him, he was swiftly taken along a
winding passage leading from the underground room, until the sharp
voice of Bird Burrnock ordered a halt.
"Swing forward th' torch so's he can see wot's ahead," said the chief,
when Little Snap saw to his horror that he stood at the brink of a
huge fissure in the rock.
"'Tis bottomless, es fur es we know. At enny rate, it's deep 'nough to
send you into eternity. Now, boys, lower him over th' hole, an' let
him down till he says he's willin' to agree to our terms. Hev it over
es quick es possible."
"Look here!" exclaimed the postboy; "if you are in such haste and
time is so valuable to you, I will tell you how you can save this delay.

More Related Content

PDF
All chapter download Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 6th Edition Savitch Solutions Manual
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
All chapter download Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 6th Edition Savitch Solutions Manual
Absolute C++ 5th Edition Savitch Solutions Manual

Similar to Absolute C++ 6th Edition Savitch Solutions Manual (20)

PDF
Absolute C++ 5th Edition Savitch Solutions Manual
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
DOC
My c++
PDF
Absolute C++ 5th Edition Savitch Solutions Manual
PPTX
C++ tutorial assignment - 23MTS5730.pptx
PDF
Instantly download the full Absolute C++ 5th Edition Savitch Solutions Manual...
PDF
4 pillars of OOPS CONCEPT
PDF
Learn C# Programming - Classes & Inheritance
PPT
Encapsulation
PPT
Lecture 9
PPTX
C++ Object Oriented Programming
PPTX
Objects and Types C#
PPTX
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
PPT
Classes & objects new
PPT
Class objects oopm
PPT
Classes2
PPTX
Absolute C++ 5th Edition Savitch Solutions Manual
Absolute C++ 5th Edition Savitch Solutions Manual
Absolute C++ 5th Edition Savitch Solutions Manual
Absolute C++ 5th Edition Savitch Solutions Manual
Absolute C++ 5th Edition Savitch Solutions Manual
My c++
Absolute C++ 5th Edition Savitch Solutions Manual
C++ tutorial assignment - 23MTS5730.pptx
Instantly download the full Absolute C++ 5th Edition Savitch Solutions Manual...
4 pillars of OOPS CONCEPT
Learn C# Programming - Classes & Inheritance
Encapsulation
Lecture 9
C++ Object Oriented Programming
Objects and Types C#
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Classes & objects new
Class objects oopm
Classes2
Ad

Recently uploaded (20)

PPTX
Introduction and Scope of Bichemistry.pptx
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
PPTX
IMMUNIZATION PROGRAMME pptx
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PPTX
How to Manage Global Discount in Odoo 18 POS
PPTX
Presentation on Janskhiya sthirata kosh.
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Landforms and landscapes data surprise preview
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PPTX
ACUTE NASOPHARYNGITIS. pptx
PPTX
Strengthening open access through collaboration: building connections with OP...
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Introduction and Scope of Bichemistry.pptx
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
IMMUNIZATION PROGRAMME pptx
The Final Stretch: How to Release a Game and Not Die in the Process.
Week 4 Term 3 Study Techniques revisited.pptx
Open Quiz Monsoon Mind Game Prelims.pptx
Software Engineering BSC DS UNIT 1 .pptx
How to Manage Global Discount in Odoo 18 POS
Presentation on Janskhiya sthirata kosh.
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
NOI Hackathon - Summer Edition - GreenThumber.pptx
Landforms and landscapes data surprise preview
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
ACUTE NASOPHARYNGITIS. pptx
Strengthening open access through collaboration: building connections with OP...
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Odoo 18 Sales_ Managing Quotation Validity
Ad

Absolute C++ 6th Edition Savitch Solutions Manual

  • 1. Absolute C++ 6th Edition Savitch Solutions Manual install download https://testbankfan.com/product/absolute-c-6th-edition-savitch- solutions-manual/ Download more testbank from https://testbankfan.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit testbankfan.com to discover even more! Absolute C++ 6th Edition Savitch Test Bank https://testbankfan.com/product/absolute-c-6th-edition-savitch- test-bank/ Absolute C++ 5th Edition Savitch Solutions Manual https://testbankfan.com/product/absolute-c-5th-edition-savitch- solutions-manual/ Absolute C++ 5th Edition Savitch Test Bank https://testbankfan.com/product/absolute-c-5th-edition-savitch- test-bank/ Absolute Java 6th Edition Savitch Test Bank https://testbankfan.com/product/absolute-java-6th-edition- savitch-test-bank/
  • 3. Absolute Java 5th Edition Walter Savitch Solutions Manual https://testbankfan.com/product/absolute-java-5th-edition-walter- savitch-solutions-manual/ Absolute Java 5th Edition Walter Savitch Test Bank https://testbankfan.com/product/absolute-java-5th-edition-walter- savitch-test-bank/ Problem Solving with C++ 10th Edition Savitch Solutions Manual https://testbankfan.com/product/problem-solving-with-c-10th- edition-savitch-solutions-manual/ Problem Solving with C++ 9th Edition Savitch Solutions Manual https://testbankfan.com/product/problem-solving-with-c-9th- edition-savitch-solutions-manual/ Problem Solving with C++ 9th Edition Savitch Test Bank https://testbankfan.com/product/problem-solving-with-c-9th- edition-savitch-test-bank/
  • 4. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. Chapter 6 Structures and Classes Key Terms structure struct structure tag member name where to place a structure definition structure value member value member variable reusing member names structure variables in assignment statements structure arguments functions can return structures class object member function calling member functions defining member functions scope resolution operator type qualifier member variables in function definitions data types and abstract types encapsulation private: private member variable public: public member variable accessor function mutator function interface API implementation Brief Outline 6.1 Structures Structure Types Structures as Function Arguments Initializing Structures 6.2 Classes Defining Classes and Member Functions Encapsulation Public and Private Members
  • 5. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. Accessor and Mutator Functions Structures versus Classes 1. Introduction and Teaching Suggestions In earlier chapters, we saw the array, the first of the C++ tools for creating data structures. The other tools are the struct and the class. We saw that the array provides a homogeneous, random access data structure. This chapter introduces tools to create heterogenous data structures, namely the struct and class. While the struct and class are identical except for default access, the text takes the didactic approach of first ignoring struct function members. This chapter deals with the struct as C treats it. The text then develops the simpler ideas involved in declaration and access for the struct. Then the machinery of class creation, protection mechanisms and some ideas of encapsulation of functions with data are treated. Constructors are left to Chapter 7. 2. Key Points Structures and Structure Types. Historical note: The name struct in C++ is provided primarily for backward compatibility with ANSI C. Suppose we declare a struct, as in: struct B { int x; int y; }; The text points out that the identifier B is called the structure tag. The structure tag B carries full type information. The tag B can be used as you would use any built-in type. The identifiers x and y declared in the definition of struct B are called member names. The members are variables are associated with any variable of struct type. You can declare a variable of type B by writing1 B u; You can access member variables (as l-values) by writing u.x = 1; u.y = 2; or (as r-values) int p, q; p = u.x; q = u.y; We said in the previous paragraph that the tag B can be used as you would use any built-in type. You can pass a struct to a function as a parameter, use a struct as a function return type, and declare arrays of variables of type struct. 1 Contrast this with the C usage, struct B u;, where the keyword struct must be used in the definition of a structure variable. This use is permitted in C++ for backward compatibility with C.
  • 6. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. Our author points out that two identifiers that are declared to be of the same structure type may be assigned, with member-wise assignment occurring.2 The critical issue here is that for assignment compatibility the two structure variables must be declared with the same structure tag. In the example that follows, the types are indistinguishable from the member structure within the struct. However, C++ uses name equivalence for types, so the compiler looks at the tags in the declarations rather than the structure to determine whether one struct variable may be assigned to another. Example: struct A { int x; int y; }; struct B { int x; int y; }; A u; B v; u = v; //type error: u and v are of different types The error message from g++ 2.9.5 is: // no match for 'A& = B&' // candidates are: struct A& A::operator=(const A&) Structures as Function Arguments. Since a structure tag is a type, the tag can be used as any other type would be used. You can have arrays of structure objects, or function parameters that are call-by-value or call-by-reference, and you can use a structure a type for the return type of a function. Defining Classes and Member Functions. These remarks elaborate the ideas in the text on class and the scope resolution operator, ::. A class definition (and a struct definition as well), with the {}; define a scope within which variables and functions are defined. They are not accessible outside without qualification by the object name and a dot operator . Member functions are defined within a particular class, to be used by any object declared to be of that class, again, only with qualification by being preceded by the object name and the dot operator. To define a function whose prototype is given in a class we have to specify the scope of that class within which the function is being defined. This is done with the class tag and scope resolution operator. To say: returnTypeName class_tag::funcMemberName(argumentList) { //memberFunctionBody... } is to say "Within the scope of the class class_tag, define the function named funcMemberName that has return type returnTypeName." 2 Member-wise assignment is the default for classes and structs. A former student of mine, John Gibson coined the phrase, “Member UNWISE copy”. We will see that for classes with pointer members, member (un)wise copy is almost never what you want.
  • 7. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. The data members belong to a particular object, and function members must be called on behalf of that particular object. The object must be specified. The object is specified by using the dot operator used after the object name, before the member name or function call. Sometimes we may speak of the calling object. Encapsulation. The notion of encapsulation means, “to collect together, as if to place in a capsule”, from which we may infer the purpose, “to hide the details”. The text says a data type has a set of values to be manipulated, and sets of operations to manipulate the values, but the details are available to the user or client. A data type becomes an abstract data type if the client does not have access to the implementation details. Abstract Data Types. The notion of Abstract Data Type (ADT) has two players: the author of the ADT and the client of the ADT. The client knows only what the ADT will do, not how the ADT carries out its tasks. The author of the ADT knows only what the ADT will do for the client, but nothing about the context within which the ADT is used by the client. Information hiding is a two way hiding. The separation of implementation (known only to the class author) and the interface (the contract between ADT author and client) is vital. The other side of the coin, namely the concealment from the ADT author of the context within which the ADT will be used, is equally vital. This prevents either author from writing code that would depend on the internals written by the other programmer. Separate compilation is necessary to a) concealing implementation details and b) assigning tasks to several programmers in a team. The reason for leaving the interface and the implementation of the ADTs in the client in the text is that we do not yet know anything about separate compilation. Observe that the text almost always places declarations (prototypes) prior to use, then uses the functions in the main function, then tucks the definitions away after the main function. This has the effect of emphasizing separation of definition and declaration well before separate compilation is seen by the student. This is worth mentioning to the student. Public and Private Members. The data members of a class are part of the implementation, not part of the interface. The function members intended for use by the client are the interface. There may be helping functions for the implementation that would be inappropriate for the client to use, and so are not part of the interface. Normally the interface is made available to the client and the implementation is hidden. A struct, by default, allows access to its members by any function. A class, by default, allows access to its members only to those functions declared within the class. This default access in a struct is called public, and the default access in a class is called private. The keywords private and public help manage hiding the implementation and making the interface available to the client. These keywords are used to modify the default access to members of a class or struct. The keyword private is used to hide members. The effect of the keyword private: extends from the keyword private: to the next instance of the keyword public:. The effect of the keyword public: extends from the keyword public: up to the next instance of the keyword private:.
  • 8. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. Accessor and Mutator Functions. It is the class author who writes the accessor and mutator functions, so it is she who controls the access to the class data. If the data members were public, any function has access in any way the client wishes. Data integrity will be compromised. Structures versus Classes. This is the text’s “truth in advertising” section. Since this document is for the instructor, little distinction between structs and classes is made here. 3. Tips Hierarchical Structures. It is worth pointing out that the name spaces for hierarchical (or nested) structures are separate. The same names can be used in the containing struct as are used in the structure member. The same names can be used in two structures members at the same level. Example: Name space and hierarchical structure initialization // file: ch6test2.cc // purpose: test namespace in hierarchical structures #include <iostream> using namespace std; struct A { int a; int b; }; struct B { A c; int a; int b; }; int main() { A u = {1,2}; B v = {{3,4},4,5}; cout << "u.a = " << u.a << " u.b = " << u.b << endl; cout << "v.c.a = " << v.c.a << " v.c.b = " << v.c.b << " v.a = " << v.a << " v.b = " << v.b << endl; return 0; } This code compiles and runs as expected. The output is: u.a = 1 u.b = 2 v.c.a = 3 v.c.b = 4 v.a = 4 v.b = 5 This is, of course, a "horrible example", designed to show a worst case. One would almost never use the same identifiers in two structures while using a struct object as a member of another as we do here. However, this does serve to illustrate the idea that the name spaces for two structures are separate. (This is also true for classes as well.) In short, duplicating a member name where needed won't break a program. Initializing Structures. The previous example also illustrates that structure variables can be assigned initial values using the curly brace notation.
  • 9. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. Separate Interface and Implementation. The interface provides the API and helps abstract the implementation details from a user of the class. This allows a programmer to change the implementation without having to change other parts of the program. A Test for Encapsulation. If you can change the implementation of a class without requiring a change to the client code, you have the implementation adequately encapsulated. Thinking Objects. When programming with classes, data rather than algorithms takes center stage. The difference is in the point of view compared to students that have never programmed with objects before. 4. Pitfalls Omitting the semicolon at the end of a struct or class definition. The text points out that a structure definition is required to have a semicolon following the closing curly brace. The reason is that it is possible to define a variable of the struct type by putting the identifier between the closed curly brace, }, and the semicolon. struct A { int a; int b; } c; The variable c is of struct type A. With some compilers, this pitfall generates particularly uninformative error messages. It will be quite helpful for the student to write several examples in which the closing semicolon in a structure definition is deliberately omitted. 5. Programming Projects Answers 1. Class grading program //ch6Prg1.cpp #include <iostream> using namespace std; const int CLASS_SIZE = 5; // Problem says this is for a class, rather than one student. // Strategy: Attack for a single student, then do for an array of N // students. //Grading Program //Policies: // // Two quizzes, 10 points each // midterm and final exam, 100 points each // Of grade, final counts 50%, midterm 25%, quizes25% // // Letter Grade is assigned:
  • 10. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. // 90 or more A // 80 or more B // 70 or more C // 60 or more D // less than 60, F // // Read a student's scores, // output record: scores + numeric average + assigned letter grade // // Use a struct to contain student record. struct StudentRecord { int studentNumber; double quiz1; double quiz2; double midterm; double final; double average; char grade; }; //prompts for input for one student, sets the //structure variable members. void input(StudentRecord& student); //calculates the numeric average and letter grade. void computeGrade(StudentRecord& student); //outputs the student record. void output(const StudentRecord student); int main() { StudentRecord student[CLASS_SIZE]; for(int i = 0; i < CLASS_SIZE; i++) input(student[i]); // Enclosing block fixes VC++ "for" loop control defined outside loop { for(int i = 0; i < CLASS_SIZE; i++) { computeGrade(student[i]); output(student[i]); cout << endl; } } return 0; } void input(StudentRecord &student) { cout << "enter the student number: "; cin >> student.studentNumber; cout << student.studentNumber << endl; cout << "enter two 10 point quizes" << endl; cin >> student.quiz1 >> student.quiz2;
  • 11. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. cout << student.quiz1 << " " << student.quiz2 << endl; cout << "enter the midterm and final exam grades." << "These are 100 point testsn"; cin >> student.midterm >> student.final; cout << student.midterm << " " << student.final << endl << endl; } void computeGrade(StudentRecord& student) { // Of grade, final counts 50%, midterm 25%, quizes25% double quizAvg= (student.quiz1 + student.quiz2)/2.0; double quizAvgNormalized = quizAvg * 10; student.average = student.final * 0.5 + student.midterm * 0.25 + quizAvgNormalized * 0.25; char letterGrade[]= "FFFFFFDCBAA"; int index = static_cast<int>(student.average/10); if(index < 0 || 10 <= index) { cout << "Bad numeric grade encountered: " << student.average << endl << " Aborting.n"; abort(); } student.grade = letterGrade[index]; } void output(const StudentRecord student) { cout << "The record for student number: " << student.studentNumber << endl << "The quiz grades are: " << student.quiz1 << " " << student.quiz2 << endl << "The midterm and exam grades are: " << student.midterm << " " << student.final << endl << "The numeric average is: " << student.average << endl << "and the letter grade assigned is " << student.grade << endl; } Data for the test run: 1 7 10 90 95 2 9 8 90 80 3 7 8 70 80 4 5 8 50 70 5 4 0 40 35 Command line command to execute the text run:
  • 12. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. ch6prg1 < data Output: enter the student number: 1 enter two 10 point quizes 7 10 enter the midterm and final exam grades. These are 100 point tests 90 95 enter the student number: 2 enter two 10 point quizes 9 8 enter the midterm and final exam grades. These are 100 point tests 90 80 enter the student number: 3 enter two 10 point quizes 7 8 enter the midterm and final exam grades. These are 100 point tests 70 80 enter the student number: 4 enter two 10 point quizes 5 8 enter the midterm and final exam grades. These are 100 point tests 50 70 enter the student number: 5 enter two 10 point quizes 4 0 enter the midterm and final exam grades. These are 100 point tests 40 35 The record for student number: 1 The quiz grades are: 7 10 The midterm and exam grades are: 90 95 The numeric average is: 91.25 and the letter grade assigned is A The record for student number: 2 The quiz grades are: 9 8 The midterm and exam grades are: 90 80 The numeric average is: 83.75 and the letter grade assigned is B The record for student number: 3 The quiz grades are: 7 8 The midterm and exam grades are: 70 80 The numeric average is: 76.25 and the letter grade assigned is C The record for student number: 4 The quiz grades are: 5 8 The midterm and exam grades are: 50 70 The numeric average is: 63.75 and the letter grade assigned is D
  • 13. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. The record for student number: 5 The quiz grades are: 4 0 The midterm and exam grades are: 40 35 The numeric average is: 32.5 and the letter grade assigned is F */ 2. CounterType An object of CounterType is used to count things, so it records a count that is a nonnegative integer number. It has mutators to increment by 1 and decrement by 1, but no member allows the counter value to go negative. There is an accessor that returns the count value, and a display function that displays the count value on the screen. Apropos of confusing error messages, this one is worth comment. In compiling the code for this problem, the following warning message was generated from VC++6.0 on the last line of the following code fragment: warning: integral size mismatch in argument; conversion supplied cout << "starting at counter value " << localCounter.currentCount << "and decrementing " << MAX << " times only decrements to zero.nn"; If the error message had been on the offending line, it would have been trivial to see the missing parentheses on the second line of this code fragment. Warn the students that the error message may be given several lines after the offending bit of code. //Ch6prg2.cpp //CounterType // // The class keeps a non-negative integer value. // It has 2 mutators one increments by 1 and // the other decrements by 1. // No member function is allowed to drive the value of the counter // to become negative. (How to do this is not specified.) // It has an accessor that returns the count value, // and a display member that write the current count value // to the screen. #include <iostream> using namespace std; const int MAX = 20; class CounterType { public: void InitializeCounter(); void increment(); //ignore request to decrement if count is zero
  • 14. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. void decrement(); int currentCount(); void display(); private: int count; }; int main() { CounterType localCounter; localCounter.InitializeCounter(); { for(int i = 1; i < MAX; i++) if(i%3 == 0) // true when i is divisible by 3 localCounter.increment(); } cout << "There are " << localCounter.currentCount() << " numbers between 1 and " << MAX << " that are divisible by 3.nn"; cout << "Starting at counter value " << localCounter.currentCount( << " and decrementing " << MAX << " times only decrements to zero.nn"; { for(int i = 1; i < MAX; i++) { localCounter.display(); cout << " "; localCounter.decrement(); } } cout << endl << endl; return 0; } void CounterType::InitializeCounter() { count = 0; } void CounterType::increment() { count++; } void CounterType::decrement() { if(count > 0) count--; }
  • 15. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. void CounterType::display() { cout << count; } int CounterType::currentCount() { return count; } A run gives this output: There are 6 numbers between 1 and 20 that are divisible by 3. Starting at counter value 6 and decrementing 20 times only decrements to zero. 6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 3. A Point class A point in the plane requires two coordinates. We could choose from many coordinate systems. The two that are most familiar are rectangular and polar. We choose rectangular coordinates (two double values representing distances from the point in question to perpendicular coordinates). Conversion the internal representation of this class from rectangular to polar coordinates should be an excellent problem for students who are reasonably prepared. These members should be implemented: a) a member function, set, to set the private data after creation b) a member function to move the point a vertical distance and a horizontal distance specified by the first and second arguments. c) a member function that rotates the point 90 degrees clockwise about the origin. d) two const inspector functions to retrieve the current coordinates of the point. Document the member functions. Test with several points exercise member functions. //Ch6prg3.cpp #include <iostream> using namespace std; // Point // The members should implement // a)a member function, set, to set the private data after creation // b)a member function to move the point a vertical distance and a // horizontal distance specified by the first and second arguments. // c)a member function that rotates the point 90 degrees clockwise // about the origin. // d)two const inspector functions to retrieve the current coordinates // of the point. // Document the member functions. // Test with several points exercise member functions.
  • 16. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. class Point { public: //set: set x to first, y to second void set(int first, int second); //move point horizontally by distance first //move vertically by distance second void move(int first, int second); //rotate point 90 degrees clockwise void rotate(); // returns the first coordinate of the point double first(); // returns the second coordinate of the point double second(); private: double x; double y; }; double Point::first() { return x; } double Point::second() { return y; } void Point::set(int first, int second) { x = first; y = second; } void Point::move(int first, int second) { x = x + first; y = y + second; } void Point::rotate() { double tmp = x; x = -y; y = tmp; } int main() { Point A, B, C; A.set(1,2); cout << A.first() << ", " << A.second() << endl;
  • 17. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. A.rotate(); cout << A.first() << ", " << A.second() << endl; A.rotate(); cout << A.first() << ", " << A.second() << endl; A.rotate(); cout << A.first() << ", " << A.second() << endl; A.rotate(); cout << A.first() << ", " << A.second() << endl; A.rotate(); cout << A.first() << ", " << A.second() << endl; B.set(2,3); cout << B.first() << ", " << B.second() << endl; B.move(1,1); cout << B.first() << ", " << B.second() << endl; C.set(5, -4); cout << C.first() << ", " << C.second() << endl; cout << "Move C by -5 horizontally and 4 vertically. " << endl; C.move(-5, 4); cout << C.first() << ", " << C.second() << endl; return 0; } In this execution of the program: We start with (1,2). This point is rotated 90 degrees, four times, getting back to the original point. The point (3,4) is set and moved by (1,1), that is, one up, one right). A second point, (5,-4) is set and moved by (-5,4) one left, on down. Then we move it back to the origin, (0,0). The output from this run is: 1, 2 -2, 1 -1, -2 2, -1 1, 2 -2, 1 2, 3 3, 4 5, -4 Move C by -5 horizontally and 4 vertically. 0, 0 4. A Gas Pump Simulation The model should have member functions that a) display the amount dispensed b) display the amount charged for the amount dispensed c) display the cost per gallon d) reset amount dispensed and amount charged to 0 prior to dispensing e) dispense fuel. Once started the gas pump continues to dispense fuel, continually keeping track of both amount of money charged and amount of fuel dispensed until stopped. f) a control to stop dispensing. The implementation was carried out as follows:
  • 18. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. 1) Implement a class definition that models of the behavior of the gas pump. 2) Write implementations of the member functions. 3) Decide whether there are other data the pump must keep track of that the user should not have access to. Parts a) b) c) d) are straightforward to implement. Part e), the pumping operation is a little tricky. Once I realized that the valve on the nozzle must be held to continue to dispense gas, I decided to model that behavior by repeatedly pressing <CR> is an easy step. Tweaking the appearance and behavior detail is all that was left. The tweaking was not trivial. There are notes in the GasPump class definition that are addressed to the instructor. These concern members that should be declared static or should have been members of a manager class that is a friend of this class. The student is not likely to understand these notes. I suggest that you delete these remarks if you give this solution to the student. #include <iostream> using namespace std; class GasPump { public: void initialize(); // set charges, amount dispensed, and //gasInMainTank to 0. void reset(); // set charges and amount dispensed to 0; void displayCostPerGallon(); //If there is only one grade, of gasoline, this should be a static //member of GasPump, since it would then apply to all instances of //GasPump. If there are several grades, then this and costPerGallon //should be ordinary members. void displayGasNCharges(); // Dispense member continually updates display of new amount and // new charges void dispense(); void stop(); // If called, stops dispensing operation. // My implementation never used this. private: double gasDispensed; double charge; public: //Perhaps these functions should be static members of this class. //See the earlier comment about this. void setPricePerGallon(double newPrice); void buyFromJobber(double quantity); void displayAmountInMainTank(); private: //These variables should be static members, since //they are associated with all class instances.
  • 19. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. double gasInMainTank; double costPerGallon; }; void GasPump::displayAmountInMainTank() { cout << gasInMainTank; } void GasPump::setPricePerGallon(double newPrice) { costPerGallon = newPrice; } void GasPump::buyFromJobber(double quantityBought) { gasInMainTank += quantityBought; } void GasPump::initialize() { gasDispensed = 0; charge = 0; gasInMainTank = 0; } void GasPump::reset() { gasDispensed = 0; charge = 0; } void GasPump::displayCostPerGallon() { cout << costPerGallon; } void GasPump::displayGasNCharges() { cout << "gallons: " << gasDispensed << " $" << charge << endl; } void GasPump::dispense() { char quit; system("cls"); // Windows clear screen //system("clear"); // Unix/Linux cout << "nnDISPENSING FUELn"; displayGasNCharges(); cout << "nPress <CR> to dispense in 0.1 gallon increments. " << "nPress q or Q <CR>to terminate dispensing.n"; while(gasInMainTank > 0) {
  • 20. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. quit = cin.get(); if (quit == 'q' || quit == 'Q') break; charge += 0.1 * costPerGallon; gasDispensed += 0.1; gasInMainTank -= 0.1; system("cls"); // Windows clear screen //system("clear"); // Unix/Linux cout << "nnDISPENSING FUELn"; displayGasNCharges(); cout << "nPress <CR> to dispense in 0.1 gallon increments. " << "nPress q or Q <CR>to terminate dispensing.n"; } if(0 == gasInMainTank) cout << "Dispensing ceased because main tank is empty.n"; } int main() { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); GasPump pump; char ans; cout << "Gas Pump Modeling Programn"; pump.initialize(); pump.setPricePerGallon(1.50); pump.buyFromJobber(25); cout << "Amount of gasoline in main tank is: "; pump.displayAmountInMainTank(); cout << endl; cout << "Gasoline price is $"; pump.displayCostPerGallon(); cout << " per gallon.n"; pump.displayGasNCharges(); cout << "Press Y/y <CR> to run the dispensing model," << " anything else quits. n"; cin >> ans; if( !('Y' == ans || 'y' == ans) ) return 0; system("cls"); // Windows //system("clear"); // Unix/Linux cout << "nWelcome Customer #1n"; cout << "Press Y/y <CR> to start dispensing Fuel,” << “ other quits n"; cin >> ans;
  • 21. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. if('Y'==ans || 'y' == ans) { ans = cin.get(); // eat <cr> pump.dispense(); } cout << "Thank you. Your charges are:n" ; pump.displayGasNCharges(); cout << endl; cout << "nnAmount of gasoline remaining in main tank is: "; pump.displayAmountInMainTank(); cout << " gallonsn"; cout << "nnWelcome Customer #2n"; pump.displayGasNCharges(); cout << "Press Y/y <CR> to start dispensing Fuel," << " anything else quits dispensing. n"; cin >> ans; if('Y'==ans || 'y' == ans) { pump.reset(); // zero old charges ans = cin.get(); // eat <cr> pump.dispense(); } cout << "Thank you. Your charges are:n" ; pump.displayGasNCharges(); cout << endl; cout << "nnAmount of gasoline remaining in main tank is: "; pump.displayAmountInMainTank(); cout << " gallonsn"; return 0; } 5. Fraction Define a class for a type called Fraction. This class is used to represent a ratio of two integers. Include mutator functions that allow the user to set the numerator and the denominator. Also include a member function that returns the value of numerator / denominator as a double. Include an additional member function that outputs the value of the fraction reduced to lowest terms, e.g. instead of outputting 20/60 the method should output 1/3. This will require finding the greatest common divisor for the numerator and denominator, and then dividing both by that number. Embed your class in a test program. //fraction.cpp //This program defines a class for fractions, which stores a numerator // and denominator. A member functions allows for retrieval of the // fraction as a double and another outputs the value in lowest // terms. //The greatest common divisor is found to reduce the fraction. // In this case we use a brute-force method to find the gcd, but
  • 22. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. // a more efficient solution such as euclid's method could also be // used. #include <iostream> #include <cstdlib> using namespace std; class Fraction { public: double getDouble(); void outputReducedFraction(); void setNumerator(int n); void setDenominator(int d); private: int numerator; int denominator; int gcd(); // Finds greatest common divisor of numerator // and denominator }; // -------------------------------- // ----- ENTER YOUR CODE HERE ----- // -------------------------------- // ====================== // Fraction::getDouble // Returns the fraction's value as a double // ====================== double Fraction::getDouble() { return (static_cast<double>(numerator) / denominator); } // ====================== // Fraction::outputReducedFraction // Reduces the fraction and outputs it to the console. // ====================== void Fraction::outputReducedFraction() { int g; g = gcd(); cout << numerator / g << " / " << denominator / g << endl; return; } // ====================== // Fraction::setNumerator // Mutator to change the numerator // ====================== void Fraction::setNumerator(int n) { numerator = n; }
  • 23. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. // ====================== // Fraction::setDenominator // Mutator to change the denominator // ====================== void Fraction::setDenominator(int d) { denominator = d; } // ====================== // Fraction::gcd // Finds greatest common divisor of numerator and denominator // by brute force (start at larger of two, work way down to 1) // ====================== int Fraction::gcd() { int g; // candidate for gcd, start at the smaller of the // numerator and denominator if (numerator > denominator) { g = denominator; } else { g = numerator; } // Work down to 1, testing to see if both numerator and denominator // can be divided by g. If so, return it. while (g>1) { if (((numerator % g)==0) && ((denominator % g)==0)) return g; g--; } return 1; } // -------------------------------- // --------- END USER CODE -------- // -------------------------------- // ====================== // main function // ====================== int main() { // Some test fractions Fraction f1, f2; f1.setNumerator(4); f1.setDenominator(2); cout << f1.getDouble() << endl; f1.outputReducedFraction();
  • 24. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. cout << endl; f2.setNumerator(20); f2.setDenominator(60); cout << f2.getDouble() << endl; f2.outputReducedFraction(); cout << endl; } 6. Odometer Define a class called Odometer that will be used to track fuel and mileage for an automotive vehicle. The class should have member variables to track the miles driven and the fuel efficiency of the vehicle in miles per gallon. Include a mutator function to reset the odometer to zero miles, a mutator function to set the fuel efficiency, a mutator function that accepts miles driven for a trip and adds it to the odometer’s total, and an accessor method that returns the number of gallons of gasoline that the vehicle has consumed since the odometer was last reset. Use your class with a test program that creates several trips with different fuel efficiencies. You should decide which variables should be public, if any. //odometer.cpp //This program defines an Odometer class to track fuel and mileage. // It stores the miles driven and fuel efficient and includes // a function to calculate the number of gallons of gasoline consumed. #include <iostream> #include <cstdlib> using namespace std; class Odometer { public: void setFuelEfficiency(double newEfficiency); void reset(); void logMiles(int additionalMiles); double gasConsumed(); private: int miles; double fuel_efficiency; }; // -------------------------------- // ----- ENTER YOUR CODE HERE ----- // -------------------------------- // ====================== // Odometer::setFuelEfficiency // Sets the fuel efficiency in miles per gallon. // ======================
  • 25. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. void Odometer::setFuelEfficiency(double newEfficiency) { fuel_efficiency = newEfficiency; } // ====================== // Odometer::reset // Resets the odometer reading // ====================== void Odometer::reset() { miles = 0; } // ====================== // Odometer::addMiles // Log additional miles to the odometer. // ====================== void Odometer::logMiles(int additionalMiles) { miles += additionalMiles; } // ====================== // Odometer::gasConsumed // Calculates the gallons of gas consumed on the trip. // ====================== double Odometer::gasConsumed() { return (miles / fuel_efficiency); } // -------------------------------- // --------- END USER CODE -------- // -------------------------------- // ====================== // main function // ====================== int main() { // Two test trips Odometer trip1, trip2; void setFuelEfficiency(double newEfficiency); void reset(); void logMiles(int additionalMiles); double gasConsumed(); trip1.reset(); trip1.setFuelEfficiency(45); trip1.logMiles(100); cout << "For your fuel-efficient small car:" << endl; cout << "After 100 miles, " << trip1.gasConsumed() << " gallons used." << endl; trip1.logMiles(50);
  • 26. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. cout << "After another 50 miles, " << trip1.gasConsumed() << " gallons used." << endl; cout << endl; trip2.reset(); trip2.setFuelEfficiency(13); trip2.logMiles(100); cout << "For your gas guzzler:" << endl; cout << "After 100 miles, " << trip2.gasConsumed() << " gallons used." << endl; trip2.logMiles(50); cout << "After another 50 miles, " << trip2.gasConsumed() << " gallons used." << endl; } 7. Pizza Define a class called Pizza that has member variables to track the type of pizza (either deep dish, hand tossed, or pan) along with the size (either small, medium, or large) and the number of pepperoni or cheese toppings. You can use constants to represent the type and size. Include mutator and accessor functions for your class. Create a void function, outputDescription( ), that outputs a textual description of the pizza object. Also include a function, computePrice( ), that computes the cost of the pizza and returns it as a double according to the rules: Small pizza = $10 + $2 per topping Medium pizza = $14 + $2 per topping Large pizza = $17 + $2 per topping Write a suitable test program that creates and outputs a description and price of various pizza objects. Notes: You may wish to point out that this could be better organized using inheritance and classes for each type of pizza. // pizza.h // // Interface file for the Pizza class. const int SMALL = 0; const int MEDIUM = 1; const int LARGE = 2; const int DEEPDISH = 0; const int HANDTOSSED = 1; const int PAN = 2; class Pizza { public: Pizza(); ~Pizza() {}; int getPepperoniToppings(); void setPepperoniToppings(int numPepperoni);
  • 27. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. int getCheeseToppings(); void setCheeseToppings(int numCheese); int getSize(); void setSize(int newSize); int getType(); void setType(int newType); void outputDescription(); double computePrice(); private: int size, type, pepperoniToppings, cheeseToppings; }; // pizza.cpp // // This program implements the Pizza class and creates several // pizza objects to test it out. #include <iostream> #include "pizza.h" using namespace std; //======================== // Pizza // The constructor sets the default pizza // to a small, deep dish, with only cheese. //======================== Pizza::Pizza() { size = SMALL; type = DEEPDISH; pepperoniToppings = 0; cheeseToppings = 1; } //================================== // Accessors and Mutators Follow //================================== // -------------------------------- // ----- ENTER YOUR CODE HERE ----- // -------------------------------- int Pizza::getPepperoniToppings() { return pepperoniToppings; } void Pizza::setPepperoniToppings(int numPepperoni) { pepperoniToppings = numPepperoni; } int Pizza::getCheeseToppings() { return cheeseToppings;
  • 28. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. } void Pizza::setCheeseToppings(int numCheese) { cheeseToppings = numCheese; } int Pizza::getSize() { return size; } void Pizza::setSize(int newSize) { size = newSize; } int Pizza::getType() { return size; } void Pizza::setType(int newType) { type = newType; } //================================== // outputDescription // Prints a textual description of the contents of the pizza. //================================== void Pizza::outputDescription() { cout << "This pizza is: "; switch (size) { case SMALL: cout << "Small, "; break; case MEDIUM: cout << "Medium, "; break; case LARGE: cout << "Large, "; break; default: cout << "Unknown size, "; } switch (type) { case DEEPDISH: cout << "Deep dish, "; break; case HANDTOSSED: cout << "Hand tossed, "; break; case PAN: cout << "Pan, "; break; default: cout << "Uknown type, "; } cout << "with " << pepperoniToppings << " pepperoni toppings " << "and " << cheeseToppings << " cheese toppings." << endl; }
  • 29. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. //================================== // computePrice // Returns: // Price of a pizza using the formula: // Small = $10 + $2 per topping // Medium = $14 + $2 per topping // Large = $17 + $2 per topping //================================== double Pizza::computePrice() { double price = 0; switch (size) { case SMALL: price = 10; break; case MEDIUM: price = 14; break; case LARGE: price = 17; break; default: cout << "Error, invalid size." << endl; return -1; } price += (pepperoniToppings + cheeseToppings) * 2; return price; } // -------------------------------- // --------- END USER CODE -------- // -------------------------------- // ====================== // main function // ====================== int main() { // Variable declarations Pizza cheesy; Pizza pepperoni; cheesy.setCheeseToppings(3); cheesy.setType(HANDTOSSED); cheesy.outputDescription(); cout << "Price of cheesy: " << cheesy.computePrice() << endl; pepperoni.setSize(LARGE); pepperoni.setPepperoniToppings(2); pepperoni.setType(PAN); pepperoni.outputDescription(); cout << "Price of pepperoni : " << pepperoni.computePrice() << endl; cout << endl; }
  • 30. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. 8. Money Define a class named Money that stores a monetary amount. The class should have two private integer variables, one to store the number of dollars and another to store the number of cents. Add accessor and mutator functions to read and set both member variables. Add another function that returns the monetary amount as a double. Write a program that tests all of your functions with at least two different Money objects. #include <iostream> using namespace std; class Money { public: int getDollars(); int getCents(); void setDollars(int d); void setCents(int c); double getAmount(); private: int dollars; int cents; }; int Money::getDollars() { return dollars; } int Money::getCents() { return cents; } void Money::setDollars(int d) { dollars = d; } void Money::setCents(int c) { cents = c; } double Money::getAmount() { return static_cast<double>(dollars) + static_cast<double>(cents) / 100; } int main( ) { Money m1, m2; m1.setDollars(20); m1.setCents(35); m2.setDollars(0);
  • 31. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. m2.setCents(98); cout << m1.getDollars() << "." << m1.getCents() << endl; cout << m1.getAmount() << endl; cout << m2.getAmount() << endl; cout << "Changing m1's dollars to 50" << endl; m1.setDollars(50); cout << m1.getAmount() << endl; cout << "Enter a character to exit." << endl; char wait; cin >> wait; return 0; } 9. Money Data Hiding Do Programming Project 6.8 except remove the two private integer variables and in their place use a single variable of type double to store the monetary value. The rest of the functions should have the same headers. For several functions this will require code to convert from an integer format to appropriately modify the double. For example, if the monetary amount stored in the double is 4.55 (representing $4.55) then if the function to set the dollar amount is invoked with the value 13, then the double should be changed to 13.55. While this will take some work, the code in your test program from Programming Project 6.8 should still work without requiring any changes. This is the benefit of encapsulating the member variables. #include <iostream> using namespace std; class Money { public: int getDollars(); int getCents(); void setDollars(int d); void setCents(int c); double getAmount(); private: //int dollars, cents; // In OLD version double amount; }; int Money::getDollars() { // return dollars return static_cast<int>(amount); } int Money::getCents() { //return cents; int val = static_cast<int>(amount * 100); if (val > 0) return val % 100;
  • 32. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. // The following logic handles negative amounts else if ((val < 0) && (val > -1)) // Negative cents (no neg dollars) return val % 100; else // No neg cents (neg dollars) return -1 * (val % 100); } void Money::setDollars(int d) { int pennies = getCents(); // Current cents amount = static_cast<double>(d) + (pennies / 100.0); //dollars = d; } void Money::setCents(int c) { amount = static_cast<double>(getDollars()) + (c / 100.0); //cents = c; } double Money::getAmount() { //return static_cast<double>(dollars) + // static_cast<double>(cents) / 100; return amount; } // This main function is identical to the PP 6.8 int main( ) { Money m1, m2; m1.setDollars(20); m1.setCents(35); m2.setDollars(0); m2.setCents(98); cout << m1.getDollars() << "." << m1.getCents() << endl; cout << m1.getAmount() << endl; cout << m2.getAmount() << endl; cout << "Changing m1's dollars to 50" << endl; m1.setDollars(50); cout << m1.getAmount() << endl; cout << "Enter a character to exit." << endl; char wait; cin >> wait; return 0; }
  • 33. Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved. 10. Temperature Class Create a Temperature class that internally stores a temperature in degrees Kelvin. However, create functions named setTempKelvin, setTempFahrenheit, and setTempCelsius that takes an input temperature in the specified temperature scale, converts the temperature to Kelvin, and stores that temperature in the class member variable. Also create functions that return the stored temperature in degrees Kelvin, Fahrenheit, or Celsius. Write a main function to test your class. Use the equations below to convert between the three temperature scales. Kelvin = Celsius + 273.15 Celsius = (5/9) X (Fahrenheit - 32) #include <iostream> using namespace std; class Temperature { public: void setTempKelvin(double temp); void setTempFahrenheit(double temp); void setTempCelsius(double temp); double getTempKelvin(); double getTempFahrenheit(); double getTempCelsius(); private: double kelvin; // Internally store temp in kelvin }; void Temperature::setTempKelvin(double temp) { kelvin = temp; } void Temperature::setTempFahrenheit(double temp) { kelvin = (5.0 * (temp - 32) / 9) + 273.15; } void Temperature::setTempCelsius(double temp) { kelvin = temp + 273.15; } double Temperature::getTempKelvin() { return kelvin; } double Temperature::getTempCelsius() { return kelvin - 273.15; } double Temperature::getTempFahrenheit() {
  • 34. Exploring the Variety of Random Documents with Different Content
  • 35. "Good-morning, Mr. Rimmon. I s'pose ye heerd what th' judge sed las' evenin' thet I'm to carry th' mail arter this. I hev resigned the Tree office, so it's all regular. Seein' I'm new to th' bizness, I thought mebbe ye wouldn't object to lettin' me start a leetle arly th' fust time." "I shall object, most decidedly, Mr. Shag." "Hev yit yer own way, Mr. Rimmon, though ye'll find I ain't a boy to be run over. Ye'll let me hev it at six sharp, or thar'll be war in th' United States camp." To this the postmaster made no reply, while one and all waited the outcome of this trying scene. In the midst of the fearful ordeal the sun rose above the crest of the distant mountains, and then a murmur ran along the expectant crowd. "It's six o'clock!" cried Sheriff Brady, consulting his watch. "The time is up, Mrs. Lewis, and the boy has not come, as I knew he wouldn't. I have kept my word, and you cannot expect any more." "It's six!" exclaimed Dan Shag, moving uneasily in his saddle. "Hand over thet mail bag, Mr. Rimmon, fer ye can't hol' it enny longer." The postmaster cast a last, anxious gaze down the road before he replied, and then a cry of great relief left his lips. "He is coming!" Eagerly the spectators looked down the road, and a murmur of joy arose on the air, as they saw the figure of a horse galloping rapidly toward the town. But the look of relief on the faces of all turned to one of dread expectancy, as they discovered that the creature was riderless! It was Jack, the postboy's favorite steed, his sides covered with foam, and his breath coming in quick, short gasps, as he sped like the wind toward his home, but Little Snap was not on his back!
  • 36. CHAPTER XVI. A LONELY NIGHT RIDE. During this long, anxious night how has it fared with Little Snap? Is the return of Jack without him a good or an evil omen? Let us see. His most direct course to Volney was by the post road to Greenbrier, after which he must take a more southerly direction by following the left bank of the Little Kanawha to the Blue Stone River. From this junction he was to ride ten miles within sound of this stream, when he must leave the river road for one leading over the hills to the east. Though there was no moon, the night was made pleasant by a myriad of stars in the mellow autumn sky, so he rode on with a hopeful heart that he should have no trouble in finding his way. Not a light was to be seen at Daring's Diamond, but quite unexpectedly a dim blaze shone from Hollow Tree, though he had not supposed the postmaster had had time to get home from Six Roads. But every moment was of value to him, so he dashed past the lonely place without slackening his pace, until he reached the homely village of Greenbrier. Even then he was rushing on at the same headlong pace he had followed since leaving home, when suddenly a familiar voice arrested his flight.
  • 37. "What in the name of George Washington are you riding like that for, Dix Lewis?" The speaker was a Mr. Renders, whom Little Snap had always considered friendly to him, so he reined in Fairy and quickly explained the object of his long ride. "I am afraid it will prove a wild-goose ride, Dix, but I wish you success. Say, I'll tell you how I can help you. I have a brother living at the corner of the Blue Stone and Mountain roads, and he has a horse you can get to finish your journey with, and leave yours there to rest till you come back. I think it is about ten miles from my brother's to Volney. A shift of horses will come in mighty handy about that time. Let me write a line to Joe, which will make your chances doubly sure." Mr. Renders wasn't long in carrying out his intentions, and, thanking him for his kindness, the postboy again urged Fairy on, the trusty Jack keeping beside his mate without attention from his master. The Little Kanawha road was an extremely lonely one, but being nearly level, Little Snap sped on with unabated speed. Thus he had swung around a sharp bend in the highway, when he was surprised by a beseeching voice calling out: "Hold up, mister, a minute! Don't be scart, for I ain't a highwayman, but I want a ride!" The speaker rose so nearly from the middle of the road that Jack had to shy in order to avoid running over him. "I can't go no farther, mister! so please have pity on me." Owing to the thick growth by the roadside, it was too dark for the boy rider to distinguish the features of the stranger. He was a burly framed man, and seemed to be shabbily dressed. He carried a short, heavy stick, whether for a cane or a weapon of defense Little Snap had no time to consider.
  • 38. "You have a spare horse," continued the other, without giving the postboy opportunity to reply to him. "Let me ride him, and you'll do the greatest favor of your life. It is a case of got to with me, or I would not ask it. I am on my way to see a dying mother, and I have walked till I can't get one foot ahead of the other any longer." He had caught hold of Jack's rein, for Little Snap had put a bridle on the horse before starting, and he was in the act of climbing into the saddle. "Hold on, sir!" exclaimed Dix Lewis, sharply. "I do not doubt your honesty——" "It's a case of must, mister! Let me ride him if for only a mile. He's doing you no good." "I have got a long journey ahead—so long that I must have him fresh to help me get there. I am sorry to refuse you." "It's such a small thing I ask of you, and you can do it just as well as not. Think if your mother was dying and you were thirty miles from her, and you should ask a man to let you ride a spare horse he had to see her. I will give you a hundred dollars if you will let me ride ten miles." Uttered in a pleading, earnest tone, the words touched the postboy's heart. "Where do you wish to go?" "To the town of Volney. If you are any acquainted there you may know Marion Calvert. He is my cousin. My name is Atwin, and I live in Frankfort." "You know Marion Calvert? I am going to see him!" "You don't say so! Perhaps you are a relation of his?" "No, sir. I am going to see him on business. Every moment is precious to me, too, for I must get back before morning." "I am sorry to have bothered you, but it was a case of necessity. You are going to let me ride?"
  • 39. Little Snap was never so puzzled in his life. While not wishing to refuse the man, he still knew it would jeopardize his chances of getting back to Six Roads in season. While he hesitated a moment, the stranger moved nearer Jack, and gathering himself to spring into the seat, said: "I shall never—whoa! Stand still, you brute!" Jack had begun to step backward, and flinging up his head, broke the man's hold from the bridle. Then uttering a snort, Jack darted forward to Little Snap's side. "What sort of a confounded hoss have you got here?" cried the unknown, again seizing the bridle, this time leaping nimbly into the saddle. "What is the trouble, Jack, old boy?" asked his master, wondering at the creature's singular and unusual action. No sooner had the stranger gained the seat than the horse sprang abruptly to one side, and rearing into the air, sent the man flying heels over head into the bushes by the roadside. All of this was done so suddenly that Little Snap had not found time to express his amazement. As if impelled by a newborn fear, Jack bounded up the road, with a whinny of terror. "Hi, there! help—quick—he'll get away from me!" cried the man, staggering to his feet and bursting through the bushes into the road. Though startled by this unexpected turn in affairs, the postboy had presence of mind enough to see that the stranger was no longer a supplicant for favors, but that a fierce determination to gain his ends was apparent on his features and in his voice. He started to catch hold of Fairy's bridle, but with a snort of defiance the creature threw back her head, and Little Snap, reading the other's purpose, touched her smartly with the spur.
  • 40. At that moment the tramp of feet came from the growth, and the burly figures of three or four men sprang into sight.
  • 41. CHAPTER XVII. LITTLE SNAP'S DISAPPOINTMENT. "He's getting away!" shouted the man who had hailed the postboy. "Come on, you lubbers!" If Little Snap had been taken off his guard at first, he was wide awake enough now, and giving Fairy an encouraging cry, he was borne swiftly away by the fleet-footed mare. Glancing back once more, he saw the four men in pursuit of him, but as long as they were on foot, he had but little to fear from them. With their hoarse shouts ringing in his ears, he sped around a curve in the road and out of their sight. After he had gone a couple of miles, finding that he was not likely to be troubled by their pursuit, he slackened Fairy's speed, and improved his first opportunity to bend over and pat Jack's head close beside him, saying: "Noble boy, you knew more than your master that time. I wonder where I should be now if you hadn't read that fellow's intentions better than I did? I wasn't quite satisfied with him, but his story did throw me off my guard. I have got to keep my eyes open sharper than that." Talking thus, half to his animal friends and half to himself, he rode swiftly on toward Volney, the soft, clayey soil muffling the hoof strokes of his horses so that they gave back no sound, his advance scarcely breaking in upon the silence of the night.
  • 42. Soon after his escape from the waylayers, whom he judged the men to be, he shifted upon Jack, giving Fairy a rest. To his joy he at last came to what he was confident was the corner of the Blue Stone and Mountain roads spoken of by Mr. Renders. If he had had any lingering doubts about this, they were driven away at sight of a farmhouse standing back a short distance from the latter highway and nearly concealed by a clump of trees, and which he knew must be the house of Mr. Renders' brother. An unnatural stillness seemed to hang over the place, and at first he was inclined to ignore Mr. Renders' advice and keep on. But he knew only too well that Jack and Fairy needed all the rest they could get before completing their long journey. Accordingly, he advanced boldly to the door, and seizing the heavy brass knocker, he raised a noise that must have aroused every inmate of the house. Heads quickly began to appear from the windows, until he imagined he had awakened a house full of people. "Who's there, and what is wanted at this unseemly hour?" demanded a voice he felt sure belonged to the host. Little Snap quickly explained his situation, and as he finished speaking, handed Mr. Renders the note sent by his brother. "Wait till I can strike a light, when I will read it, and if I think favorable of what he says, I will be out in a moment." Then the window was closed, while a minute later a light shone from the apartment. This last soon began to move about, and it was not long before the door was opened, when Mr. Renders appeared fully dressed. "Hope you will excuse my delay, but I didn't keep you waiting longer than I could help. So you have come from Six Roads?" "Yes, sir; and I have got to get back there before six o'clock this morning, or I would never have troubled you."
  • 43. "Never mind that. I have called better men than I am out of their nests on worse nights than this. In regard to a horse, I have one which can take you to Volney and back in one hour, though I don't care about having you crowd him quite as hard as that, unless it is necessary." "I will not hurt the horse. Can you let me have him? I will pay you well——" "A fig for the pay! Dismount and turn your animals into that pen. I claim a horse can rest better by having a chance to move about if he wants to. I will feed them as soon as they have cooled off somewhat. I will lead out my horse." Hardly able to comprehend that he was so well favored, Little Snap did as he was told, and by the time he had seen Fairy and Jack in comfortable quarters, Mr. Renders had his horse ready for him to spring into the saddle. "He may need a little urging, but don't spare him. It is eleven miles to Volney, and he is good for the trip and return without any more stop than you will wish to make with Mr. Calvert. I think you will be fortunate enough to find that gentleman at home." Mr. Renders then described Mr. Calvert's house to him, so he would have no difficulty in finding it, when Little Snap began the second stage of his journey. The road now more broken than it had been since leaving Greenbrier, Little Snap rode on over hill and through valley, finding the horse loaned him by Mr. Renders an exceptionally fine animal. He had consulted his watch to find it was a quarter of two, when he looked ahead to see what he believed to be the village of Volney. "Almost there," he muttered. "How glad I am. Now if I find Mr. Calvert at home I shall be soon on my return journey. That is the house Mr. Renders described, I am sure. How still it looks around it!" Speaking his thoughts thus aloud, Little Snap dashed into the spacious grounds surrounding the quaint, old-fashioned dwelling he
  • 44. supposed was the home of the man he had ridden so far to see. The occupant of the house proved to be more wakeful than he had expected, for he had barely pulled rein under the enormous willow growing by the door before a chamber window was opened, and a man's voice demanded. "Who's there?" "My name is Lewis, and I am from Union Six Roads. Does Mr. Calvert live here?" "That's my name, sir, though I do not recognize yours." "I carry the mail on the Kanawha route. Of course, you remember Dix Lewis, to whom you sub-let the line?" "Wait a minute and I'll be down there." Giving the finishing touches to his toilet, as he appeared, Mr. Calvert soon opened the heavy door and stepped out into the night. He was a man in the vicinity of forty, with a frank, good-natured looking countenance, who seemed rather brusque in his movements and manner of speaking. "I hardly remember your countenance, Mr. Lewis," he said, as he stepped forward and extended his right hand; "but that is nothing strange, as we never met but that once. What in the name of Congress has brought you here at this unexpected hour? But excuse me, dismount, put your horse in the barn, and come into the house before you begin your talk. I would call one of the negroes, but they are so sleepy at this time of night they are no good." "I can't stop," said Little Snap, as soon as he could find an opportunity to speak. "I have to get back to Six Roads in season to take the mail to the Loop to-day." "You won't do it, all the same. But what's up?" The postboy then made the other acquainted with all that had happened, interrupted several times by Mr. Calvert, who finally exclaimed:
  • 45. "A bad pickle, I should say. But I am glad you have come to me. Of course the only thing for you to do is to get out of it." "I cannot do that with honor to myself," said Little Snap, who had not expected this from the contractor. "It would look as if I was really to blame for all they have said." "Better let it look like that than to get your neck in the halter, or a bullet through your head." The postboy could not help showing his surprise. Was it for this he had ridden so far, and with such high-colored hopes? He had not dreamed of anything other than assistance from the man who was behind him in his undertaking.
  • 46. CHAPTER XVIII. A PERILOUS UNDERTAKING. "You will go up to Six Roads and see what can be done?" he asked, while his hopes sank lower and lower. "I can't. Say, tell you what I will do. I am intending to start for Washington to-day; but when I get through there, and it won't take me more than a week. I will come back by way of the Six Roads. I wish I had let the plaguey route alone." "That will be too late to help me," said Little Snap. "I tell you, you want to get out of it as quick as you can. Let this Shag you speak of carry the mail until I can get around." "I am afraid you do not understand the situation, Mr. Calvert. There is some sort of a conspiracy to rob the government, and this Dan Shag is one of those at the bottom of it." "Oh, nonsense! you have your suspicions and jump at conclusions. It may be that some of them are trying to crowd you a little, seeing you are a boy, but we all have to put up with such things. We laugh at them when we grow older. Come into the house and have some refreshments and a few hours' sleep before you attempt your long journey home. Jove! you showed good grit in undertaking it." "I undertook it in the good faith that you would stand by me in this affair, Mr. Calvert, and though it is worth something for me to know how you feel about it, I am disappointed to find you do not care for the welfare of the route, for whose success or failure you are really responsible."
  • 47. "You are pretty blunt, I will say that for you. I am inclined to think you will be a hard one for them to bluff down." "I shall stand up for my rights, Mr. Calvert, as long as I can. Can't you come to Six Roads before you go to Washington? They are expecting you." "You said Mr. Warfield still stands by you?" "Yes, sir." "Then, I think I can fix you all right. I will give you a note to him to stand by you until I come to town, though I still advise you to get out of it." Little Snap saw that it was no use to urge him more, so he remained silent, while Mr. Calvert hastily scribbled away on a slip of paper he took from his pocket. When he had finished, he read: "Volney, Va., Sept. 18. "Mr. Jason Warfield, Union Six Roads, Va. "Dear Sir: Stand by the bearer of this, Mr. Dix Lewis, in his troubles as far as you think prudent, until I can see you. Your obt. servant, Marion Calvert." "There, I think that will do the business. Sorry you don't feel like coming in to rest until daylight. It's a long, lonesome ride before you." Thanking him, Little Snap took the piece of paper, and carefully placing it in one of his pockets, he wheeled the horse about to start homeward. "Hold on!" cried Mr. Calvert, as the postboy gained the road. Little Snap turned the horse and galloped back into the yard, wondering and hoping.
  • 48. "I wanted to say that you will no doubt see the wisdom of my advice before you get home." "If that is all you have to say to me farther, Mr. Calvert," said our hero, somewhat sharply, "I will bid you good-night! My name is at stake in this matter, and I will know the right and the wrong of it before I am driven out." The postboy spoke more sharply than he intended, but the other's last words had cut like a knife. Without waiting for a reply, he touched the horse smartly with the spurs and sped down the road at a furious pace. "I should know he was a Lewis if I hadn't heard his name," muttered the mail contractor, as he watched the boyish rider out of sight. "I ought to have known better than to have let him fool with the business at the outset, but Rimmon said he could do it. Well, I must get ready for my start to the capital." His hopes crushed, so far as expecting any aid from Mr. Calvert was concerned, Little Snap pursued his homeward journey with a gloomy mind. Since midnight the sky had become overcast, so it was quite dark—too dark for him to note his surroundings with any clearness. The ride back as far as Mr. Renders' seemed shorter than he had expected, and he found that gentleman awaiting his coming. "You went pretty quick, but Jim don't show his journey a bit. I tell you that horse can't be beat very easy. Pay? I don't want a red cent. I have fed your horses, so they are all right to start. How'd you find Calvert? He's cranky sometimes, but a fairly good sort of a fellow as men go. Wish he might go to Congress rather than that old Warfield. Never liked that old duffer; he's deceitful. Nothing of that kind about Cal. Hello! Starting?" While Mr. Renders had been running on in his sort of haphazard way, Little Snap had put the saddle on Jack's back and sprung into the seat.
  • 49. "I wish you would take pay for the use of your horse, Mr. Renders, but if you won't, I am a thousand times obliged to you, and I hope I can do you a favor some time. Good-night." "He's right after his business!" said the other to himself, as the clatter of horses' hoofs died out in the distance. "That boy is bound to succeed." Riding swiftly homeward, Little Snap was saying to his dumb companions: "I have to fight my own battles, and this trip has been for nothing. No; not for nothing, for I know just what to do now. You needn't crowd on quite so hard, Jack; we have plenty of time." Shifting from one animal to the other when he thought best, Little Snap rode on through the night, unmindful of the gathering stormclouds, though he kept a sharp gaze as he drew near the lonesome spot where he had been accosted by the stranger. Not a sound broke the deathlike silence, save the dull tramp of his horses' feet, and with a feeling of relief he had soon left the place a mile behind. At Greenbrier the postboy shifted steeds, giving Jack another rest, intending to return to him at Daring's Diamond. No one was astir at this place yet, neither was there any sign of life at Hollow Tree. But he hadn't gone a dozen rods beyond the Tree before a sharp voice commanded him to stop, and he suddenly found his way blocked with a body of armed men. Three or four caught upon Fairy's bit with a force which dragged her back upon her haunches, and Little Snap was nearly pulled from his seat. Realizing his desperate situation, the postboy dextrously slipped the bridle from the mare's head, at the same time shouting for her to rush on. Rallying, she made the wild attempt, and Jack, having already cleared a way through the party, she followed upon his heels.
  • 50. Shots rang about the fleeing postboy's head, some of the bullets flying uncomfortably near, but he fancied he was going to get away, when he dashed furiously down the descent leading to Greenbrier bridge. As he came in sight of the stream with its high, precipitous banks, a cry of dismay left his lips. Every bridge plank had been removed, and only the stringers spanned the dark chasm of foaming waters! Retreat cut off, with no possible chance to ford the stream, Little Snap saw at a glance that he was rushing into a veritable deathtrap! The cries of his pursuers rang exultantly in his ears.
  • 51. CHAPTER XIX. THE BUSHBINDERS' PLANS. Little Snap's first impulse, as he saw the trap into which he had been driven, was to turn at bay and meet his enemies in a hand-to-hand struggle, as hopeless as his chances were. But at that moment Jack had reached the bank of the stream, and the fleeing horse, instead of checking his speed or turning aside, sped like an arrow out over one of the bridge stringers toward the other side! The postboy was not far behind the gallant steed, but he had opportunity to see the horse rush safely the length of the timber, to reach the clear way beyond. With a snort, as if of triumph, Jack renewed his swift flight now in comparative safety. The sight of this feat caused the hopes of Little Snap to rise, and he resolved to follow the example set by his equine friend. "On, Fairy!" he cried; "it is our only chance!" The pursuers suddenly stopped, as they beheld with amazement the daring deed attempted by the fugitive. Fairy, seeming to realize the desperate part she was to act in the startling undertaking, rushed fearlessly in the steps of her mate. Sitting firmly in his saddle, the postboy felt himself carried out over the dark chasm, and he caught a gleam of the foaming waters hurling their forces madly against the rock walls of the channel. The
  • 52. next instant he felt a quiver run through the frame of the faithful steed, and he knew that she was falling! Under the weight of her burden the mare somehow missed her footing, her feet slipped on the treacherous way, and she tried in vain to recover her equilibrium. Finding that she was falling, Little Snap freed his feet from the stirrups just as horse and rider shot headlong into the boiling river! At that moment the pursuing party halted on the bank of the stream, amazed witnesses of the mishap. Little Snap was carried completely over a stringer running parallel with the first, and, lighter than the horse, struck in the water farther down the stream. Fortunately, he escaped the jagged rocks of the banks, though the fall deprived him for a time of his senses. When he came to a realization of his situation, he found himself struggling in a mass of débris which had clogged the river a short distance below the crossing. In the midst of his efforts to extricate himself, he heard a voice just above him. Then, as he peered out from his retreat, he saw some of his enemies coming rapidly toward the place. "I can see him!" cried the foremost. "I knew he came down this way." "Give up, younker!" called another voice. "Ye mought as well, fer we air sure to git yer." Letting go the branch upon which he had found himself clinging, Little Snap hoped to elude his foes by swimming down the stream. But he found himself so entangled in the mass of floating wood about him, that before he could get clear, the party was in the water beside him. A sharp struggle ensued, but at its end the postboy was dragged out of the water by the hands of the Burrnock gang.
  • 53. "Bind him, boys!" said the leader, exultantly. "That's gittin' him what I call mighty easy. I tole yer the bridge racket would fix him." "What do you mean by this treatment?" demanded the postboy, as he found himself bound hands and feet. "Keep cool an' ye'll find out quick 'nough, younker. Tote him erlong, boys." Little Snap looked for some trace of Fairy, but in vain. Nothing further was said by his captors, while he was borne away into the depths of the forest, subject to such thoughts and feelings as may be imagined. What would they think at home of his non- appearance when the time for his return came? Then he thought of Jack, and wondered if the horse would keep on until he had reached Six Roads. He was certain the steed would, and this gave him the only hope he felt in his captivity. At last the captors and their prisoner reached the little opening marking the top of the bluff overhanging the cave, where Little Snap had once sought Ab Raggles. In the party which had effected his capture he saw Buzzard and Hawk Burrnock, while the leader of the gang was none other than he who had been chief spokesman in the cavern. This man the postboy soon found was Bird Burrnock, the father of the four brothers. As soon as the underground room was reached, Bird Burrnock addressed the captive as follows: "Time is too mighty short, younker, fer us to perlaver with yer. 'Tis true we mought hev saved a good leetle slice o' yit by knockin' ye in th' head when we pulled ye out'n th' river. To speak th' truth, I hoped th' river would fix yer; but seein' yit wan't likely to, we got round in season to take enny idee o' escape ye mought hev hed out yer head. "We know yer air wanted mighty bad up to th' Roads, but we want yer wuss hyur, though they air playin' inter our hands. Still, yer
  • 54. mought give 'em th' slip. Yer can't us! But this ain't bizness. "To say nothin' o' th' shabby way yer treated th' boys, we hev a double puppose in gittin' yer inter our grips. Yit don't make enny difference to ye wot it is, so long es 'tis so. Now we hev got yer, we hev got a leetle proposition to make yer, on which yer future happiness depends, es th' parson would say. "'Tan't enny use fer me to deny, but we hev got our eye on thet mail route, 'cos we think yit can be made a mighty payin' investment. Shag wants to run in shacks with us, but we like yer grit well 'nough to make a bargain with ye. Now, if ye'll 'gree to stand in with us, an' do th' square thing, we'll not only give ye a shake in th' profits, but we'll see thet ye don't hev enny trubble. All ye'll hev to do will be to stop yer hoss long 'nough fer us to look th' baggage over. Mind ye, we do th' sortin'. Further, we promise thet ye won't hev enny further trubble at Six Roads, or ennywhere else. Is't a trade, younker?" Little Snap was so amazed at this audacious scheme that at first he could not find tongue to reply to Bird Burrnock. "What if I refuse to enter into any such a contract?" "Then our own safety demands thet we put ye where ye can't trubble us enny more. But ye won't?" "I'll not stand in with you!" At this declaration the little knot of listeners started excitedly, and Bird Burrnock, the leader, uttered a fearful oath. "Then ye wanter die, younker?" he hissed. "Of course I do not, sir! But I cannot lend my aid to any such infamous scheme. Why, it's robbery of the worst sort, and you cannot carry it on for any length of time without being caught." "Thet's our lookout. Mebbe ye air shaky in thet direction, but I can tell yer we air well heeled thet way. Why, th' most' influential citizens o' th' Roads air in with us. There's th' judge, an' the colonel. Then,
  • 55. too, we'll take keer o' Shag. Once more, will yer fall with th' plan, or shall we be 'bliged to take desprit measures with yer?" Little Snap realized that he was in the power of men who would hesitate at nothing to carry out their unlawful purpose, and he thought of his mother even then anxiously awaiting his return home, and imagined the anguish she would feel upon his failure to come. He thought of his father, so helpless to aid the others, and his younger sister and brother, and the sorrow they would experience. Still, with these sad reflections in his mind, and the dread consequence if he refused to comply with the demands of his captors plainly before him, he hesitated but a moment in his reply. "I cannot accept your terms." "Fetch erlong th' rope, boys," ordered Bird Burrnock, tersely. "I reckon 'twon't take us long to change his mind."
  • 56. CHAPTER XX. A STARTLING DISCOVERY. Buzzard Burrnock quickly entered one of the dark recesses of the cavern, returning a moment later with a coil of rope on his arm. "Make a loop in one end," commanded the elder Burrnock. "Be lively, too, fer we don't want to fool with him hyur all day." When the rope had been arranged to their satisfaction, the noose was slipped over Little Snap's shoulders, so the cord encircled his body under the arms. "Drag him to th' pit!" cried the leader. "Reckon a leetle consideration there'll take th' starch out'n him." Buzzard Burrnock and Hawk seized hold of the postboy, one on either side, and half dragging him, he was swiftly taken along a winding passage leading from the underground room, until the sharp voice of Bird Burrnock ordered a halt. "Swing forward th' torch so's he can see wot's ahead," said the chief, when Little Snap saw to his horror that he stood at the brink of a huge fissure in the rock. "'Tis bottomless, es fur es we know. At enny rate, it's deep 'nough to send you into eternity. Now, boys, lower him over th' hole, an' let him down till he says he's willin' to agree to our terms. Hev it over es quick es possible." "Look here!" exclaimed the postboy; "if you are in such haste and time is so valuable to you, I will tell you how you can save this delay.