100% found this document useful (2 votes)
166 views

C for C programmers 3rd Edition Pohl 2024 Scribd Download

programmers

Uploaded by

catribotsev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
166 views

C for C programmers 3rd Edition Pohl 2024 Scribd Download

programmers

Uploaded by

catribotsev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Download the full version of the ebook at

https://ebookultra.com

C for C programmers 3rd Edition Pohl

https://ebookultra.com/download/c-for-c-
programmers-3rd-edition-pohl/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C for Game Programmers Noel Llopis

https://ebookultra.com/download/c-for-game-programmers-noel-llopis/

ebookultra.com

C by Dissection Ira Pohl

https://ebookultra.com/download/c-by-dissection-ira-pohl/

ebookultra.com

C 2008 For Programmers Third Edition Deitel Developer


Series Deitel

https://ebookultra.com/download/c-2008-for-programmers-third-edition-
deitel-developer-series-deitel/

ebookultra.com

Professional JavaScript for Web Developers 3rd Edition


Nicholas C. Zakas

https://ebookultra.com/download/professional-javascript-for-web-
developers-3rd-edition-nicholas-c-zakas/

ebookultra.com
PHP Cookbook Solutions Examples for PHP Programmers 3rd
Edition David Sklar

https://ebookultra.com/download/php-cookbook-solutions-examples-for-
php-programmers-3rd-edition-david-sklar/

ebookultra.com

DeathDay 3rd Edition William C. Dietz

https://ebookultra.com/download/deathday-3rd-edition-william-c-dietz/

ebookultra.com

Android 6 for Programmers An App Driven Approach 3rd


Edition Paul Deitel

https://ebookultra.com/download/android-6-for-programmers-an-app-
driven-approach-3rd-edition-paul-deitel/

ebookultra.com

Physics for Engineers and Scientists Vol 2 3rd Edition


Hans C. Ohanian

https://ebookultra.com/download/physics-for-engineers-and-scientists-
vol-2-3rd-edition-hans-c-ohanian/

ebookultra.com

Basic Tactics for Listening Teacher s Book 3rd Edition


Jack C. Richards

https://ebookultra.com/download/basic-tactics-for-listening-teacher-s-
book-3rd-edition-jack-c-richards/

ebookultra.com
C for C programmers 3rd Edition Pohl Digital Instant
Download
Author(s): Pohl, Ira
ISBN(s): 9780201395198, 0201395193
Edition: 3
File Details: PDF, 22.25 MB
Language: english
Digitized by the Internet Archive
in 2019 with funding from
Kahle/Austin Foundation

https://archive.org/details/cforcprogrammersOOOOpohl
Programmers
Third Edition
Programmers
Third Edition

Ira Pohl
University of California, Santa Cruz

A
▼▼
ADDISON-WESLEY

An Imprint of Addison Wesley Longman, Inc.


Reading, Massachusetts • Harlow, England • Menlo Park,
California • Berkeley, California • Don Mills, Ontario
Sydney • Bonn • Amsterdam • Tokyo • Mexico City
W '7G,7
Many of the designations used by manufacturers and sellers to distinguish their
products are claimed as trademarks. Where those designations appear in this
book, and Addison Wesley Longman, Inc. was aware of a trademark claim, the
designations have been printed in initial capital letters or all capital letters.

The author and publisher have taken care in preparation of this book, but make
no expressed or implied warranty of any kind and assume no responsibility for
errors or omissions. No liability is assumed for incidental or consequential
damages in connection with or arising out of the use of the information or
programs contained herein.

The publisher offers discounts on this book when ordered in quantity for
special sales. For more information, please contact:

Corporate, Government, and Special Sales


Addison Wesley Longman, Inc.
One Jacob Way
Reading, Massachusetts 01867
(718) 944-3700

Library of Congress Cataloging-in-Publication Data


Pohl, Ira
C++ for C Programmers / Ira Pohl.-3rd ed.
p. cm.
Includes bibliographical references and index.
ISBN 0-201-39519-3
1. C++ (Computer program language) I. Title.
QA76.73.C153P654 1999
005.13'3-dc21 98-37980
CIP

Copyright © 1999 by Addison Wesley Longman, Inc.

All rights reserved. No part of this publication may be reproduced, stored in a


retrieval system, or transmitted, in any form or by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior written
permission of the publisher. Printed in the United States of America. Published
simultaneously in Canada.

ISBN 0-201-39519-3
Text printed on recycled and acid-free paper
123456789 10-MA—0201009998
First printing, November 1998
To Laura and her mother
Preface xvii

Chapter 1 An Overview of C++ and Object-Oriented Programming 1


1.1 Object-Oriented Programming.2
1.2 Why Learn C++?.3
1.3 C as a Starting Point.4
1.4 Classes and Abstract Data Types.6
1.5 Constructors and Destructors.9
1.6 Overloading.10
Dissection of the operator+() Function.11
1.7 Inheritance.12
1.8 Moving from C++to Java.14
Dissection of the improved Program.15
1.9 Benefits of Object-Oriented Programming.16
1.10 Pragmatics.17
Summary.18
Review Questions.19
Exercises.19

Chapter 2 Native Types and Statements 23


2.1 Program Elements.24
2.1.1 Comments.24
2.1.2 Keywords.25
2.1.3 Identifiers.25
2.1.4 Literals.26
2.1.5 Operators and Punctuators.28
2.2 Input/Output.29
2.3 Program Structure.30
2.4 Simple Types.32
2.4.1 Initialization.33
2.5 The Traditional Conversions.34
2.6 Enumeration Types.38
2.6.1 typedef Declarations.39
2.7 Expressions.39
viii ▼ Contents

2.8 Statements.43
2.8.1 Assignment and Expressions.44
2.8.2 The Compound Statement.45
2.8.3 The i f and i f-el se Statements.45
2.8.4 The whi le Statement.46
2.8.5 The for Statement.47
2.8.6 The do Statement.49
2.8.7 The break and conti nue Statements.49
2.8.8 The switch Statement.51
2.8.9 The goto Statement.52
2.9 Pragmatics.53
2.10 Moving from C++to Java.55
Dissection of the Moon Program.56
Summary.57
Review Questions.59
Exercises.60

Chapter 3 Functions, Pointers, and Arrays 65


3.1 Functions.65
3.1.1 Function Invocation.66
3.2 Function Definition.66
3.3 The return Statement.68
3.4 Function Prototypes.68
3.4.1 Recursion.69
3.5 Default Arguments.70
3.6 Functions as Arguments.71
3.7 Overloading Functions.72
3.8 Inlining.73
3.9 Scope and Storage Class.74
3.9.1 The Storage Class auto.76
3.9.2 The Storage Class extern.76
3.9.3 The Storage Class regi ster.78
3.9.4 The Storage Class static.78
3.9.5 linkage Mysteries.80
3.10 Namespaces.80
3.11 Pointer Types.82
3.11.1 Addressing and Dereferencing.83
3.11.2 Pointer-Based Call-by-Reference.83
Dissection of the order() Function.84
3.12 Reference Declarations and Call-by-Reference.85
3.13 The Uses of void.87
▼ Contents IX

3.14 Arrays and Pointers. 89


3.14.1 Subscripting.90
3.14.2 Initialization.90
3.15 The Relationship Between Arrays and Pointers.91
3.16 Passing Arrays to Functions.92
3.17 The char* String: A Kernel Language ADT.93
3.18 Multidimensional Arrays.95
3.19 Assertions and Program Correctness.96
3.20 Free-Store Operators new and delete.97
Dissection of the dynarray Program.99
3.21 Pragmatics.100
3.21.1 Vector Instead of Array.100
3.21.2 String Instead of char*.101
3.22 Moving from C++to Java.102
Dissection of the SumArray Program.103
Summary.104
Review Questions.106
Exercises.107

Chapter 4 Classes 115


4.1 The Aggregate Type struct and class.115
4.2 Structure Pointer Operator.117
4.3 Member Functions.118
4.4 Access: Private and Public.120
4.5 Classes.121
4.6 Class Scope.122
4.6.1 Scope Resolution Operator.122
4.6.2 Nested Classes.124
4.7 An Example: Flushing.12 5
4.8 stati c and const Members.128
Dissection of the salary Program.131
4.8.1 Mutable Members.132
4.9 The thi s Pointer.133
4.10 Unions.134
4.11 Bit Fields.135
4.12 A Container Class Example: ch_stack.136
4.13 Pragmatics.138
4.14 Moving from C++to Java.139
Summary.141
Review Questions.142
Exercises.143
x ▼ Contents

Chapter 5 Constructors and Destructors 149


5.1 Classes with Constructors.150
5.1.1 The Default Constructor.151
5.1.2 Constructor Initializer.152
5.1.3 Constructors as Conversions.152
5.1.4 Improving the point Class.153
5.2 Constructing a Dynamically Sized Stack.154
5.2.1 The Copy Constructor.156
5.3 Classes with Destructors.157
5.4 An Example: Dynamically Allocated Strings.158
Dissection of the my_stri ng Class.160
5.5 The Class dbl_vect.163
5.5.1 dbl_vect as a Linear Vector Type.165
5.6 Members That Are Class Types.166
5.7 Example: A Singly Linked List.168
Dissection of the print() and release() Lunctions . . .170
5.8 Two-Dimensional Arrays.173
5.9 Polynomials as a Linked List.174
5.10 Strings Using Reference Semantics.181
5.11 No Constructor, Copy Constructor, and Other Mysteries .... 183
5.11.1 Destructor Details.184
5.12 Pragmatics.185
5.13 Moving from C++to Java.186
Summary.187
Review Questions ..188
Exercises.189

Chapter 6 Operator Overloading and Conversions 195


6.1 ADT Conversions.196
6.2 Overloading and Lunction Selection.197
Dissection of the rational Program.199
6.3 friend functions.200
6.4 Overloading Operators.203
6.5 Unary Operator Overloading.204
6.6 Binary Operator Overloading.207
6.7 Overloading Assignment and Subscripting Operators.209
Dissection of dbl_vect:: operator=() function . . . .211
6.8 Polynomial: Type and Language Expectations.213
6.9 Overloading I/O Operators « and ».215
6.10 Overloading Operator () for Indexing.216
Dissection of the Class mat ri x.218
6.11 Overloading the Pointer Operator ->.219
▼ Contents xi

6.12 Overloading new and delete.220


6.13 Pragmatics.223
6.13.1 Signature Matching.224
6.14 Moving from C++to Java.226
Summary.228
Review Questions.229
Exercises.230

Chapter 7 Templates, Generic Programming, and STL 239


7.1 Template Class stack.240
7.2 Function Templates.242
7.2.1 Signature Matching and Overloading.244
7.3 Class Templates.245
7.3.1 Friends.246
7.3.2 Static Members.246
7.3.3 Class Template Arguments.246
7.3.4 Default Template Arguments.247
7.3.5 Member Templates.248
7.4 Parameterizing the Class vector.248
7.5 STL.252
7.5.1 STL Example Code.252
7.6 Containers.254
7.6.1 Sequence Containers.255
Dissection of the stLvectProgram.256
7.6.2 Associative Containers.257
7.6.3 Container Adapters.257
7.7 Iterators.258
7.7.1 The istream_iterator and ostream_iterator . .259
7.7.2 Iterator Adapters.260
7.8 Algorithms.261
7.8.1 Sorting Algorithms.261
7.8.2 Nonmutating Sequence Algorithms.262
7.8.3 Mutating Sequence Algorithms.263
7.8.4 Numerical Algorithms.264
7.9 Numerical Integration Made Easy.264
7.10 Pragmatics. 266
7.11 Moving from C++ to Java.267
Summary.268
Review Questions.269
Exercises.269
xii ▼ Contents

Chapter 8 Inheritance 273


8.1 A Derived Class.274
8.2 Typing Conversions and Visibility.276
8.3 Virtual Functions.279
8.4 Abstract Base Classes.283
8.5 Templates and Inheritance.289
8.6 Multiple Inheritance.290
8.7 Inheritance and Design.293
8.7.1 Subtyping Form.294
8.7.2 Code Reuse.295
8.8 Runtime Type Identification.295
8.9 Pragmatics.297
8.10 Moving from C++to Java.298
Summary.301
Review Questions.302
Exercises.303

Chapter 9 Exceptions 307


9.1 Using the assert Library.307
9.2 C++Exceptions.308
9.3 Throwing Exceptions.309
9.3.1 Rethrown Exceptions.311
9.3.2 Exception Expressions.312
9.4 Try Blocks.313
9.5 Handlers.314
9.6 Exception Specification.315
9.7 terminate() and unexpectedf).315
9.8 Example Exception Code.316
9.9 Standard Exceptions and Their Uses.318
9.10 Pragmatics.320
9.11 Moving from C++to Java.321
Summary.323
Review Questions.324
Exercises.325

Chapter 10 OOP Using C++ 327


10.1 OOP Language Requirements.327
10.1.1 ADTs: Encapsulation and Data Hiding.328
10.1.2 Reuse and Inheritance.329
10.1.3 Polymorphism.330
10.2 OOP: The Dominant Programming Methodology.331
10.3 Designing with OOP in Mind.332
10.4 Class-Responsibility-Collaborator.333
10.5 Design Patterns.334
▼ Contents xiii

10.6 Moving from C++to Java.336


Summary.338
Review Questions.340
Exercises.341

Appendix A ASCII Character Codes 343

Appendix B Operator Precedence and Associativity 34S

Appendix C Language Guide 347


C.l Program Structure.347
C.2 Lexical Elements.348
C.2.1 Comments.349
C.2.2 Identifiers.349
C.2.3 Keywords.350
C.3 Constants.350
C.4 Declarations and Scope Rules.354
C.5 Namespaces.356
C.6 Linkage Rules.357
C.7 Types.359
C.8 Conversion Rules and Casts.361
C.9 Expressions and Operators.364
C.9.1 sizeof Expressions.365
C.9.2 Autoincrement and Autodecrement Expressions . . .365
C.9.3 Arithmetic Expressions.366
C.9.4 Relational, Equality, and Logical Expressions . . . .366
C.9.5 Assignment Expressions.368
C.9.6 Comma Expressions.369
C.9.7 Conditional Expressions.369
C.9.8 Bit-Manipulation Expressions.370
C.9.9 Address and Indirection Expressions.370
C.9.10 new and delete Expressions.371
C.9.11 Other Expressions.373
C.10 Statements.374
C.l0.1 Expression Statements.376
C.10.2 The Compound Statement.376
C.10.3 The i f and i f-el se Statements.376
C.l0.4 The while Statement.377
C.10.5 The for Statement.377
C.10.6 The do Statement.378
C.10.7 The break and continue Statements.379
C.10.8 The switch Statement.379
C.10.9 The goto Statement.380
C.10.10 The return Statement.381
C.l0.11 The Declaration Statement.381
XIV ▼ Contents

C.ll Functions.382
C.ll.l Prototypes.383
C.11.2 Call-by-Reference.383
C.ll.3 Inline Functions.384
C.11.4 Default Arguments.384
C.11.5 Overloading.384
C.11.6 Type-Safe Linkage for Fmictions.386
C.12 Classes.387
C.12.1 Constructors and Destructors.387
C.12.2 Member Functions.389
C.12.3 Friend Functions.389
C.12.4 The thi s Pointer.390
C.12.5 Operator Overloading.390
C.12.6 stati c and const Member Functions.392
C.12.7 Mutable.392
C.13 Inheritance.393
C.13.1 Multiple Inheritance.395
C.13.2 Constructor Invocation.396
C.13.3 Abstract Base Classes.396
C.13.4 Pointer to Class Member.396
C.13.5 Runtime Type Identification.398
C.13.6 Virtual Functions.399
C.14 Templates.400
C.14.1 Template Parameters.402
C.14.2 Function Template.403
C.14.3 Friends.404
C.14.4 Static Members.404
C.14.5 Specialization.404
C.15 Exceptions.405
C.15.1 Throwing Exceptions.406
C.15.2 Try Blocks.407
C.15.3 Handlers.408
C.15.4 Exception Specification.408
C.15.5 termi nate() and unexpected().409
C.15.6 Standard Library Exceptions.409
C.16 Caution and Compatibility.409
C.16.1 Nested Class Declarations.410
C.16.2 Type Compatibilities.410
C.16.3 Miscellaneous.410
C.17 New Features in C++.411
▼ Contents xv

Appendix D Input/Output 413


D.l The Output Class ost ream.413
D.2 Formatted Output and iomanip.414
D.3 User-Defined Types: Output.418
D.4 The Input Class i stream.420
D.5 Files.422
D.6 Using Strings as Streams.425
D.7 The Functions and Macros in ctype.426
D.8 Using Stream States.427
D. 9 Mixing I/O Libraries.429

Appendix E STL and String Libraries 431


E. l Containers.431
E.1.1 Sequence Containers.433
E.l.2 Associative Containers.434
E.1.3 Container Adapters.436
E.2 Iterators.437
E.2.1 Iterator Categories.437
E.2.2 Iterator Adapters.438
E.3 Algorithms.440
E.3.1 Sorting Algorithms.440
E.3.2 Nonmutating Sequence Algorithms.442
E.3.3 Mutating Sequence Algorithms.444
E.3.4 Numerical Algorithms.446
E.4 Functions.448
E.4.1 Function Adapters.450
E.5 Allocators.451
E.6 String Library.452
E.6.1 Constructors.454
E.6.2 Member Functions.454
E.6.3 Global Operators.459

References 461

Index 463
.
The book uses an evolutionary teaching process, with C as a starting point and C++
as a destination. It can also be used by those already familiar with other similar pro¬
gramming languages, such as Pascal, PL/1, or BASIC. The reader can stop and use
the language facilities at various points in the text.
This book will get the C programmer up and running in C++ in the shortest pos¬
sible time. The teaching-by-equivalency method used enables the C programmer to
immediately convert existing code to C++. Working code is emphasized. A program
particularly illustrative of the chapter’s themes is analyzed by dissection, which is
similar to a structured walk-through of the code. Dissection explains to the reader
newly encountered programming elements and idioms.
C is a general-purpose programming language that was originally designed by
Dennis Ritchie of Bell Laboratories and implemented there on a PDP-11 in 1972. C
was first used as the systems language for the UNIX operating system. Ken Thomp¬
son, the developer of UNIX, had been using both an assembler and a language
named B to produce initial versions of UNIX in 1970.
C++, invented at Bell Labs by Bjarne Stroustrup in the mid-1980s, is a powerful
modern successor language to C. C++ adds to C the concept of class, a mechanism
for providing user-defined types, also called abstract data types. C++ supports
object-oriented programming by these means and by providing inheritance and run¬
time type binding. C++ is increasingly the choice of scientists and engineers in
developing scientific software.
This book, intended for use in a first course in C++ programming, can be used
as a supplementary text in an advanced programming, data structures, software
methodology, comparative language, or other course in which the instructor wants
C++ to be the language of choice. Each chapter presents a number of carefully
explained programs.
All of the major pieces of code were tested. A consistent and proper coding
style is adopted from the beginning and is one chosen by professionals in the C++
community. The code is available at the Addison Wesley Longman Web site
(www.awl.com/cseng/titles/0-201-39519-3/).
For the programmer who wants C experience, this book could be used in con¬
junction with A Book on C, 4th ed., by A1 Kelley and Ira Pohl (Addison-Wesley, 1998).
As a package, the two books offer a unique, integrated treatment of the C and C++
programming languages and their use.
XV111 t Preface

This book incorporates a number of important features.

■ An evolutionary approach. The C programmer can immediately benefit


from programming in C++. Chapter 1, “An Overview of C++ and Object-
Oriented Programming,” provides an introduction to the use of C++ as an
object-oriented programming language. Chapter 2, “Native Types and State¬
ments,” reviews the kernel language, which is mostly C with some improve¬
ments. Chapter 3, “Functions, Pointers, and Arrays,” continues with
similarities between functions and complex data types. The middle chapters
show how to use classes, which are the basis for abstract data types and
object-oriented programming (OOP). The later chapters give advanced
details of the use of inheritance, templates, and exceptions. At any point in
the text, the programmer can stop and use the new material.

■ Teaching by example. The book is a tutorial that stresses examples of


working code. Right from the start, the student is introduced to full working
programs. An interactive environment is assumed. Exercises are integrated
with the examples to encourage experimentation. Excessive detail is avoided
in explaining the larger elements of writing working code. Each chapter has
several important example programs. Major elements of these programs are
explained by dissection.

■ Data structures in C++. The text emphasizes many of the standard data
structures from computer science. Stacks, safe arrays, dynamically allocated
multidimensional arrays, lists, trees, and strings are all implemented. Exer¬
cises extend the student’s understanding of how to implement and use
these structures. Implementation is consistent with an abstract data type
approach to software.

■ Object-oriented programming. The reader is led gradually to the object-


oriented style. Chapter 1, “An Overview of C++ and Object-Oriented
Programming,” discusses how the C programmer can benefit in important
ways from a switch to C++ and object-oriented programming. Object-
oriented concepts are defined, and the way in which these concepts are
supported by C++ is introduced. Chapter 4, “Classes,” introduces classes,
which are the basic mechanism for producing modular programs and
implementing abstract data types. Class variables are the objects being
manipulated. Chapter 8, “Inheritance,” develops inheritance and virtual
functions, two key elements in this paradigm. Chapter 10, “OOP Using C++,”
discusses OOP programming philosophy. This book develops in the
programmer an appreciation of this point of view.
t Preface xix

C equivalence. Where appropriate, C++ code is given with equivalent C


code. This gives the experienced C programmer immediate access to idio¬
matic C++ code.

New Java equivalence. At the end of each chapter is a discussion of how


the C++ programmer can very naturally and easily begin programming in
Java, a language of interest for work on the Internet. The Java programming
language borrows ideas from C++ and is designed to run in a machine- and
system-independent manner. This makes it suitable for Internet work, such
as writing applets for Web pages that are used by browsers. Because Java is
an extension of C++, it is readily learned by the C++ programmer.

ANSI C++ language and iostream. For an existing, widely used language,
C++ continues to change at a rapid pace. This book is based on the most
recent standard: the ANSI C++ Committee language documents. A succinct
informal language reference is provided in Appendix C, “Language Guide.”
Use of the iostream library is featured in Appendix D, “Input/Output,” and
STL is featured in Appendix E, “STL and String Libraries.”

Standard template library (STL). STL is explained and used in Chapter 7,


“Templates, Generic Programming, and STL,” and in Appendix E, “STL and
String Libraries.” Many of the data structure examples foreshadow its expla¬
nation and use. There is a strong emphasis on the template mechanism
required for STL and the iterator idiom that STL exploits.

Industry- and course-tested. This book is the basis of many on-site profes¬
sional training courses given by the author, who has used its contents to
train professionals and students in various forums since 1986. The various
changes are course-tested and reflect the author’s considerable teaching
and consulting experience. The text is the basis for Web-based training in
C++ available from

www. digitalth ink. com

Exercises. The exercises test and often advance the student’s knowledge of
the language. Many are intended to be done interactively while reading the
text, encouraging self-paced instruction.
XX t Preface

■ Web site. The examples both within the book and at Addison-Wesley’s Web
site are intended to exhibit good programming style. The Addison-Wesley
Web site for this book contains the programs in the book, as well as adjunct
programs that illustrate points made in the book or flesh out short pieces of
programs. The programs available at the Web site are introduced by
their .cpp or .h names and can be obtained by referencing

www.awl.com/cseng/titles/0-201 -39519-3/

My special thanks go to my wife, Debra Dolsberry, who encouraged me through¬


out this project. She acted as book designer and technical editor for this edition. She
developed appropriate formats and style sheets in FrameMaker 5.5 and guided the
transition process from my other books on C++. She also implemented and tested
all major pieces of code.
This book was developed with the support of my editor, J. Carter Shanklin, and
editorial assistant, Angela Buenning.

Ira Pohl
University of California, Santa Cruz
r 1
Overview of C++
and Object-Oriented
Programming
This chapter gives a brief overview of C++ and provides an introduction to its use as
an object-oriented programming language (OOP). Like the rest of the book, it
assumes a knowledge of C. The chapter presents a series of programs of increasing
complexity and carefully explains the elements of each; program examples in the
later sections illustrate some of the concepts of object-oriented programming. This
approach should give students or professional C programmers a sense of how C++
works. As an overview, this chapter makes use of advanced material that can be
skimmed or skipped by readers who wish to begin with the elementary concepts
found in the next chapter.
Each feature of C++ is explained briefly. The examples in this chapter give read¬
ers simple, immediate, hands-on experience with key features of the C++ language.
The chapter introduces stream I/O, operator and function overloading, classes, con¬
structors, destructors, and inheritance to give programmers the flavor of writing
C++. Mastery of individual topics requires a thorough reading of the later chapters.
Object-oriented programming is today’s programming methodology of choice.
OOP is the product of 30 years of programming practice and experience, going back
to Simula 67 and continuing with SmallTalk and, more recently, Eiffel, Java, and
C++. The OOP programming style captures the behavior of the real world in a way
that hides detailed implementation. When successful, OOP allows the problem
solver to think in terms of the problem domain.
C++ was created by Bjarne Stroustrup in the mid-1980s. Stroustrup had two
main goals: (1) to make C++ compatible with ordinary C and (2) to extend C with
OOP constructs based on the class construct of Simula 67. C, developed by Dennis
Ritchie in the early 1970s as a system-implementation language to build UNIX, grad¬
ually gained popularity not only as a system-implementation language, but also as a
general-purpose language.
C programmers can readily use structured programming methodology, which
involves writing large programs as a series of procedure calls on properly struc¬
tured data. C has a limited form of data abstraction. The C struct declaration
allows programmers to declare user-defined aggregates with understandable
2 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

names. As a powerful extension of these concepts, the C++ class declaration pro¬
vides strong typing, data hiding, and code reuse through inheritance. Also, C++
allows programming teams to program in the large, using the techniques of file
encapsulation, function encapsulation, and class encapsulation. As a consequence,
C++ can be used to teach modular-programming habits within the object-oriented
paradigm.

1.1 Object-Oriented Programming


Object-oriented programming is a data-centered view of programming in that data
and behavior are strongly linked. Data and behavior are conceived of as classes
whose instances are objects. For example, a polynomial can have a range of legal
values that can be affected by such operations as addition and multiplication.
OOP views computation as simulating behavior. What is simulated are objects
represented by a computational abstraction. Suppose that we wish to improve our
poker play; to do so, we must better understand the odds of obtaining various
poker hands. We need to simulate card shuffling and must have appropriate ways to
speak about cards and suits. Publicly, we use the suit names: spades, hearts, dia¬
monds, and clubs. Privately, these suits are internally represented as integers. This
internal choice is hidden and consequently should not affect our computation. Just
as decks of cards can have many physical compositions and still properly behave as
cards, so too can computational card decks.
We will be using the terms abstract data type (ADT) and object-oriented pro¬
gramming (OOP) to refer to a powerful new programming approach. An ADT is a
user-defined extension to the existing types available in the language. An ADT con¬
sists of a set of values and a collection of operations that can act on those values.
For example, C++ does not have a native complex number type but instead uses the
class construct to define such a type in the complex library. Objects are class vari¬
ables. Object-oriented programming allows ADTs to be easily created and used. OOP
uses the mechanism of inheritance to conveniently derive a new type from an exist¬
ing user-defined type. This mechanism is akin to biological taxonomies. For exam¬
ple, both rodents and cats are mammals; if the category mammal is an encoding of
the information and behavior true for all objects in this class, creating the catego¬
ries cat and rodent from the category mammal is an enormous saving.
In OOP, objects are responsible for their behavior. For example, polynomial
objects, complex number objects, integer objects, and floating-point number
objects can all be added. Each type has code for executing addition. The compiler
provides the right code for integers and floating-point numbers. The polynomial
ADT has a function defining addition specific to its implementation. The ADT pro¬
vider should include code for any behavior the object can be commonly expected to
1.2 ▼ Why Learn C++? 3

understand. Making an object responsible for its behavior eases the coding task for
the user of that object.
Consider a class of objects called shapes. If we want a shape to draw on a
screen, we need to know where the shape is to be centered and how to draw. Some
shapes, such as polygons, are relatively easy to draw. A general shape-drawing rou¬
tine can be very expensive, requiring storage for a large number of individual
boundary points. Avoiding this in the polygon case is clearly beneficial. If the indi-
\idual shape object knows best how to draw itself, the programmer using such
shapes needs only to invoke the object’s drawing function.
The new class construct in C++ provides the encapsulation mechanism to imple¬
ment ADTs. Encapsulation includes both the internal implementation details of a
specific type and the externally available operations and functions that can act on
objects of that type. The implementation details can be made inaccessible to code
that uses the type. For example, a stack might be implemented as a fixed-length
array, whereas the publicly available operations would include push and pop.
Changing the internal implementation to a linked list should not affect how push
and pop are used externally. Code that uses the ADT is called client code for the
ADT. The implementation of a stack is hidden from its clients. The details of how to
provide data hiding in classes are introduced here and are developed thoroughly in
Chapter 4, “Classes,” and in Chapter 8, “Inheritance.”

1.2 Why Learn C++?


C++ supports the object-oriented programming style, a major advance over the
structured programming style supported by such languages as C, Pascal, and
FORTRAN. A chief cost is the increased complexity of the C++ language, however.
C++ is a more complex language but better suited to developing large software
projects.
C is a procedural, imperative language that has a small set of built-in types and
limited forms of type extensibility. These types are well suited to system
programming. For many problem domains, however, C’s usefulness is hampered by
its lack of type extensibility. C++ remedies these limitations by allowing arbitrary
user-defined types. The increased complexity of C++ is one of its biggest drawbacks.
Although this increase reflects the large number of necessary new ideas, it makes
mastery more difficult. To overcome this problem, this book approaches the
learning process by gradually transforming the C programmer into a practiced C++
programmer.
4 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

1.3 C as a Starting Point


C is the kernel language that C++ was built on. Indeed, most C programs are correct
C++ programs as is; in some sense, the C programmer is therefore already a C++
programmer.
C++ is a marriage of the low level and the high level. C was designed to be a
systems-implementation language, one close to the machine. C++ adds object-
oriented features that are designed to allow a programmer to create or to import a
library appropriate to the problem domain. The user can write code at the level
appropriate to the problem while maintaining contact with the machine-level imple¬
mentation details.
The following C program uses a function to perform simple output:

In file hello.c

/* Hello World in C
* by Charles Codeman
*/ ‘

#include <stdio.h>

void pr_message(char* message)


{
printf("%s\n", message);
}

int main()
{
pr_message("Hello world!");
}

Here is the equivalent C++ program:

In file hellol.cpp

//Hello world in C++


// by Olivia Programmer

#include <iostream> //IO library


#include <string> //string type
using namespace std;
1.3 t C as a Starting Point 5

inline void pr_message(string s = "Hello world!")


{ cout « s « endl; }

int main()
{
pr_message();
}

When executed, this program prints the following message:

Hello world!

A C++ program is a collection of declarations and functions that begin executing


with the function mai n(). The C++ program is compiled after the preprocessor exe¬
cutes #-designated directives. The preprocessor precedes the phase during which
the compiler translates the resulting program into machine code. The #include
directive found in the example program hellol.cpp imports any needed files, usually
library definitions. In this case, the I/O library for a typical compiler system is found
in the file iostream. The string type is found in the standard library defined in the
file string. On new C++ systems, these files are wrapped in namespace std. The
using declaration allows such names to be used without std: : prepended to each
name. The include files could also have been coded without namespace and usi ng,
as follows:

#include <iostream.h> //IO library


#include <string.h> //C++ string type

This text will use the namespace convention for include files. In most instances, the
inclusion of the header files will not be shown in program code.
The // symbol is used as a rest-of-line comment symbol. Also, the program text
can be placed in any position on the page, with white space between tokens being
ignored. White space, comments, and indentation of text are all used to create a
humanly readable, well-documented program but do not affect program semantics.
An efficiency concern for the C++ programmer is that the inline modifier of
the function pr_message() is used to tell the compiler to compile this function
without resort to function call and return instructions, if possible. As written, the
pr_message() function had a string parameter s, whose default value was
“Hello worl d! ”. This means that when passed an empty or a void parameter list,
pr_message("Hello world!") is executed.
The identifier cout is defined in iostream as the standard output stream con¬
nected by most C++ systems to the screen for output. The identifier endl is a stan¬
dard manipulator that flushes the output buffer, printing everything to that point
6 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

while going to a new line. The operator << is the put to output operator, which
writes out what comes after it to cout.
A function in C++ has a return type that can be voi d, indicating that no value is
to be returned, as is the case with pr_tnessage(). The special function main()
returns an integer value to the runtime system, which in the implicit case found
here, is 0, meaning that termination was normal.
Consider the following variation to mai n():

In file hello2.cpp

int main()
{
pr_message();
pr_message("Laura Pohl");
pr_message("It is dinner time.");
}
The program, when executed, prints the following message:

Hello world!
Laura Pohl
It is dinner time.

1.4 Classes and Abstract Data Types


OOP is a balanced approach to writing software. Data and behavior are packaged
together. This encapsulation creates user-defined types, which extend and interact
with the native types of the language. Type extensibility is the ability to add to the
language user-defined types that are as easy to use as native types.
An abstract data type, such as a complex number, is a description of the ideal
public behavior of the type. The user of a complex number knows that operations,
such as add or print, result in certain public behaviors. Operations add and print are
called methods. A concrete implementation of the ADT also has implementation lim¬
its; for example, complex numbers are limited in precision. These limits affect pub¬
lic behavior. Also, internal, or private, details of the implementation do not directly
affect the user’s understanding. For example, a complex number is frequently
implemented as a set of two floating-point variables; their names should be of no
direct consequence to the user.
Encapsulation is the ability to hide internal detail while providing a public inter¬
face to a user-defined type. C++ uses declarations class and struct in conjunction
1.4 T Classes and Abstract Data Types 7

with the access keywords private, protected, and public to provide encapsula¬
tion. C does not have access modifiers, but its struct is the basis for the class
extensions in C++.
OOP terminology is strongly influenced by SmallTalk programming. The
SmallTalk designers wanted programmers to break with their past habits and to
embrace a new programming methodology. They invented such terms as message
and method to replace the traditional terms function invocation and member
function.
Public members are available to any function within the scope of the class
declaration. Public members provide the type’s interface. Private members are
available for use only by other member functions of the class. Privacy allows the
implementation of a class type to be hidden, which prevents unanticipated
modifications to the data structure. Restricted access, or data hiding, is a feature of
object-oriented programming.
Let us write a class called complex that will implement a restricted form of com¬
plex number.

In file complexl.cpp

//An elementary implementation of type complex

class complex {
Public: //universal access to interface
void re_assign(double r) { real = r; }
void im_assign(double im) { imaginary = im; }
void print() const
{ cout « "(" « real «
« imaginary « "i)" « endl; }
friend complex operator+(complex, complex);
private: //restricted access to implementation
double real, imaginary;
};

The hidden representation is two variables of type doubl e.


The declaration of member functions allows the ADT to have particular func¬
tions act on its private representation. For example, the member function pri nt()
outputs a complex number as a comma-separated pair of doubles. The imaginary
part of the number has the suffix iTThe member function re_assign() stores the
real part of a complex number into the hidden variable real, and the member func¬
tion im_assi gn() stores the imaginary part of a complex number into the hidden
variable imagi nary. Member functions, such as pri nt(), that do not modify mem¬
ber variables’ values are declared const. The friend function operator+O decla¬
ration will be used later to implement the definition of the addition of two complex
8 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

numbers (see Section 1.6, “Overloading,” on page 11). The friend designation
means that the function, although not a member of class compl ex, has access to all
of its members.
We can now use the data type compl ex as if it were a basic type of the language.
Code that uses this type is its client. The client can use only the public members to
act on variables of type compl ex.

In file complexl.cpp

//Test of the class complex

int main()
{
complex x, y, z;

x.re_assign(9.5);
x. im_assign(-4.5);
y. re_assign(4.2);
y.im_assign(6.0);
z = x + y;
x. printO ;
y. printO ;
z. printO;
}
Variables x, y, and z are of type complex. The member functions are called
using the dot, or structure member, operator. As is seen from their definitions,
these member functions act on the hidden private-member fields of the named vari¬
ables. The output of this example program is

(9.5,-4.5i)
(4.2,6i)
(13.7, 1.5i)
1.5 ▼ Constructors and Destructors 9

1.5 Constructors and Destructors


In OOP terminology, a variable is called an object. A constructor is a member func¬
tion that initializes an object of its class. In many cases, this involves dynamic stor¬
age allocation. Constructors are invoked whenever an object of a particular class is
created. A destructor is a member function that finalizes a variable of its class. As
we shall see later, in many cases this involves dynamic storage deallocation. If you
are not familiar with these concepts, you may want to skip this material for now and
wait until the later chapters, where they are explained in detail.
Let’s change our compl ex example by adding a constructor to initialize its value.
We will also add a destructor to provide debugging output when a compl ex object is
destroyed.

In file complex2.cpp

class complex {
public:
//constructor
complex(double r=0, double im=0): real(r), imaginary(im) { }
//destructor
~complex() { cout « "destructor called on print(); }

};

A constructor’s name is the same as the class name and is invoked when declar¬
ing variables, as in

complex x(5.5, 1.0), y;

Here, the variables are declared and initialized: x. real is initialized as 5.5 and
x. imaginary as 1.0; y. real is initialized as 0 and y. imaginary as 0. These are the
default values of the arguments passed to the constructor.
A destructor is written as a member function whose name is the class name pre¬
ceded by the tilde symbol ~. The destructor written in complex is used for debug¬
ging. The destructor calls print() to write out the value of the complex object
being destroyed. For example, if x is not changed during execution, the destructor
prints the following on exit from x’s scope:

destructor called on (5.5,li)


10 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

1.6 Overloading
Overloading is the practice of giving several meanings to an operator or a function.
The meaning selected depends on the types of arguments used by the operator or
the function. Let us overload the function pri nt() in the previous example. This
will be a second definition of the pri nt () function.

In file complexl.cpp

class complex {
public: //universal access

void print(string var_name) const


{ cout « var_name « " = print(); }

}
This version of pri nt () takes a single argument of type st ri ng and is used to print
the complex number’s variable name and value.

complex x(l.5,2);
x.print("x"); //print: x = (1.5,2i)
x.printO; //print: (1.5,2i)

It is possible to overload most of the C++ operators. For example, we will over¬
load + to mean complex addition. To do this, we need two keywords: friend and
operator. The keyword operator precedes the operator token and replaces what
would otherwise be a function name in a function declaration. The keyword fri end
gives a function access to the private members of a class variable. A fri end func¬
tion is not a member of the class but has the privileges of a member function in the
class in which it is declared.
1.6 ▼ Overloading 11

In file complex3.cpp

complex operator+(complex x, complex y)


{
complex t;

t.real = x.real + y.real;


t.imaginary = x.imaginary + y.imaginary;
return t;

int main()
{
complex x(9.5, -4.5), y(4.2,6.0), z;

z = x + y;
x. print("x")
y. print("y")
z. print ("z")

Dissection of the operator+C) Function

■ complex operator+(complex x, complex y)

The + is overloaded. Both of its arguments are of type complex. The return type is
complex, as expected.

■ complex t;

The function needs to return a value of type complex. This local variable is initial¬
ized to (0,0i) by the constructor.

■ t.real = x.real + y.real;


t.imaginary = x.imaginary + y.imaginary;
return t;

The definition adds both the real and the imaginary parts of the complex numbers
and returns them as the compl ex variable t.
12 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

1.7 Inheritance
A singular concept in OOP is the promotion of code reuse through the inheritance
mechanism. A new class is derived from an existing, or base, class. The derived class
reuses the base-class members and can add to or alter them.
Many types are variants of one another, and it is frequently tedious and error
prone to develop new code for each. A derived class inherits the description of the
base class, thus avoiding redevelopment and testing of the existing code. The inher¬
itance relationship is hierarchical. Hierarchy is a method for coping with complex¬
ity, imposing classifications on objects.
For example, the periodic table of elements has elements that are gases. These
have properties that are shared by all elements in that classification. The inert gases
are an important subclassification. The hierarchy is that an inert gas, such as argon,
is a gas, which in turn is an element. The hierarchy provides a convenient way to
understand the behavior of inert gases. We know that they are composed of protons
and electrons, as this is shared description with all elements. We know that the inert
gases are in a gaseous state at room temperature, as this behavior is shared with all
gases. We know they do not combine in ordinary chemical reactions with other ele¬
ments, as this is shared behavior of all inert gases.
As another example, consider designing a database for a college. The registrar
must track various types of students. The base class must capture a description of
student. Two main categories of student are graduate and undergraduate.

OOP Design Methodology


1. Decide on an appropriate set of types.
2. Design their relatedness into the code, using inheritance.

An example of deriving a class follows.

In file studentl.cpp

enum support { ta, ra, fellowship, other };


enum year { fresh, soph, junior, senior, grad };
1.7 t Inheritance 13

class student {
public:
student(char* nm, int id, double g, year x);
void print() const;
private:
int student_id;
double gpa;
year y;
char name[30];
};

class grad_student : public student {


public:
grad_student(char* nm, int id, double g,
year x, support t, char* d, char* th);
void print() const;
private:
support s;
char dept [10];
char thesis[80];
};

In this example, grad_student is the derived class, and student is the base class.
The use of the keyword publ i c following the colon in the derived-class header
means that the public members of student are to be inherited as public members
of grad_student. Private members of the base class cannot be accessed in the
derived class. Public inheritance also means that the derived class grad_student is
a subtype of student.
An inheritance structure provides a design for the overall system. For example,
a database containing all of the people at a college could be derived from the base
class person. The student base class could be used to derive law students as a fur¬
ther significant category of objects. Similarly, person could be the base class for a
variety of employee categories. The hierarchical inheritance structure is illustrated
in the following diagram.
14 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

Inheritance Structure

1.8 Moving from C++ to Java


This section introduces Java I/O and classes, as well as Java’s use as an object-
oriented programming language. Mastery of the individual Java topics requires a
thorough reading of a companion book such as The Java Programming Language
by Arnold and Gosling.
Object-oriented programming is implemented by the class construct. The
cl ass construct in Java is based on the cl ass construct in C++. The later examples
in this book illustrate how Java implements OOP concepts, such as data hiding,
ADTs, inheritance, and type hierarchies. Java, designed to be used on the World
Wide Web, has special libraries for graphics and communication across the Net. Java
is designed to run in a machine- and system-independent manner. This means that
the Java program will execute with the same results on a PC running Windows 95 or
on a workstation running Sun Solaris. Java does this by defining its semantics com¬
pletely in terms of a virtual machine. The job for a system that wants to run Java is
to port the virtual machine. This is a trade-off between portability and efficiency.
Additional overhead in a machine running a simulator of a different architecture is
1.8 ▼ Moving from C++to Java 15

inevitable. Some of this inefficiency can be overcome by the use of just-in-time com¬
pilers or native code written in C. On many platforms, it is also possible to use a
direct-to-native code compiler for maximum runtime efficiency.
Programs must communicate to be useful. Our first example is a program that
prints on the screen the phrase “Java is an improved C.”

In file Improved.java

// A first Java program illustrating output.


// Title: Improved
// Author: Jack Appleteer

class Improved {
public static void main (String[] args)
{
System.out.println("Java is an improved C.");
}
}
The program prints the following on the screen:

Java is an improved C.

This program is compiled using the command javac Improved.java,, resulting in


the creation of a code file named Improved.class. This file can be run by using the
command java Improved.

♦♦♦♦♦♦♦♦♦♦♦♦
Dissection of the improved Program

■ //A first Java program illustrating output.

The double slash // is the new symbol for a comment. The comment runs to the
end of the line. The old C bracketing comment symbols /* */ are still available for
multiline comments. Java also provides /** */ bracketing comment symbols for a
document comment. The program javadoc takes these document comments and
generates an HTML file.
16 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

■ class Improved {

Java programs are classes. A cl ass has syntactic form that is derived from the C
struct, which is not in Java. In Java, class identifier names, such as Improved, are
by convention capitalized. Data and code are placed within classes.

■ public static void main (Stringf] args)

A class executed as a program starts by calling the member function mai n(). In this
case, main() is a member of Improved. In Java, command line arguments are
passed in an array of Stri ngs. In C, we need an argc variable to tell the program
the number of command line arguments. In Java, this array length is found by using
args .length.

■ System.out.println("Java is an improved C.");

This statement prints to the screen. The System.out object uses the member func¬
tion pri ntl n() to print. The function prints the string and adds a new line, which
moves the screen cursor to the next line. Unlike printfO in C, pri ntl n() does
not use format controls.

In Java, all functions are contained in classes. In this case, the function mai n()
is a member of class Improved. A member function is called a method.

1.9 Benefits of Object-Oriented Programming


The central element of OOP is the encapsulation of an appropriate set of data types
and their operations. The class construct, with its member functions and data mem¬
bers, provides an appropriate coding tool. Class variables are the objects to be
manipulated.
Classes also provide data hiding. Access privileges can be managed and limited
to whatever group of functions needs access to implementation details. This pro¬
motes modularity and robustness.
Another important concept in OOP is the promotion of code reuse through the
inheritance mechanism, which derives a new class from an existing, or base, class.
The base class can be added to or altered to create the derived class. In this way, a
hierarchy of related data types can be created that share code.
1.10 ▼ Pragmatics 17

The OOP programming task is frequently more difficult than normal procedural
programming as found in C. At least one extra design step is needed before one gets
to the coding of algorithms. This step involves the design of types that are appropri¬
ate for the problem at hand. Frequently, one is solving the problem more generally
than is strictly necessary. The belief is that this extra step will pay dividends in sev¬
eral ways. The solution will be more encapsulated and thus more robust and easier
to maintain and change. It will also be more reusable. For example, where the code
needs a stack, that stack is easily borrowed from existing code. In an ordinary pro¬
cedural language, such a data structure is frequently “wired into” the algorithm and
cannot be exported.
OOP is many things to many people. Attempts at defining it are reminiscent of
the blind sages’ attempts at describing the elephant. I will offer one more definition,
an equation.

OOP = type-extensibility + polymorphism

1.10 Pragmatics
C++ compilers for ANSI C++ as described in this book are still incomplete. Make
sure you know what the vendors support, especially when it comes to recent
changes in the use of namespaces, exception handling, templates, and libraries,
especially the Standard Template Library, or STL.
Revisiting our first example, we can make it compatible with pre-namespace and
string library compilers by using char* for our strings and ordinary .h header files
for including our libraries.

In file hello2.cpp

//Hello world in C++ by Older Fogie

#include <iostream.h>

inline void pr_message(char* s = "Hello world!")


{ cout « s « endl;}

int main()
{
pr_message();
return 0;
}
18 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

This version of the program should run correctly with any available compiler. Notice
that we explicitly return 0, as we would in a C program. ANSI C++ allows this to be
implicit, the style we will use throughout the book.

Summary
1. Object-oriented programming is a data-centered view of programming, meaning
that data and behavior are strongly linked. Data and behavior are conceived of
as classes whose instances are objects.

2. An abstract data type (ADT) is a user-defined extension to the existing types


available in the language. An ADT consists of a set of values and a collection of
operations that can act on those values. For example, C++ does not have a native
complex number type but uses the class construct to define such a type in the
complex library. Objects are class variables.

3. C++ supports the object-oriented programming style. This is a major advance


over the structured programming style supported by such languages as C,
Pascal, and FORTRAN. C is a procedural, imperative language with a small set of
built-in types and limited forms of type extensibility. These types are well suited
to system programming. However, for many problem domains, C’s usefulness is
hampered by its lack of type extensibility.

4. C is the kernel language of C++. C++ is a marriage of C and object-oriented fea¬


tures that are designed to allow a programmer to create or to import a library
appropriate to the problem domain. The user can write code at the level appro¬
priate to the problem while maintaining contact with the machine-level imple¬
mentation details.

5. Encapsulation is the ability to hide internal detail while providing a public inter¬
face to a user-defined type. C++ uses the declarations cl ass and struct in con¬
junction with the access keywords private, protected, and public to provide
encapsulation. C does not have access modifiers, but its struct is the basis for
the class extensions in C++.

6. In OOP terminology, a variable is called an object. A constructor is a member


function that initializes an object of its class. In many cases, this involves
dynamic storage allocation. Constructors are invoked whenever an object of a
particular class is created. A destructor is a member function that finalizes a
variable of its class.
▼ Review Questions 19

7. A singular concept in OOP is the promotion of code reuse through the inherit¬
ance mechanism. A new class is derived from an existing, or base, class. The
derived class reuses the base-class members and can add to or alter them. The
inheritance relationship is hierarchical. Hierarchy, a method for coping with
complexity, imposes classifications on objects.

8. Java is an OOP language that also derives from C and C++. It is relatively easy to
convert C++ programs to Java. Java is more portable but runs slower than C or
C++. Java was developed at a time when the Internet started to flourish and has
many features tailored to use on the Internet.

Review Questions
1. Name three object-oriented programming languages.

2. The I/O library in C++ is used by including_.

3. The rest-of-line comment symbol is_.

4. The C++ class is an extension of the C_.

5. C was originally a SIL (systems-implementation language) used to write

6. What does the construct inline do?

7. C++was created by_in the mid-1980s.

8. Access keywords are_,_, and_.

Exercises
1. Using stream I/O, write on the screen the words

she sells seashells by the seashore

(a) all on one line, (b) on three lines, (c) inside a box.
20 Chapter 1 ▼ An Overview of C++ and Object-Oriented Programming

2. Take a working program, omit each line in turn, and run the program through
the compiler. Record the error message caused by each deletion. For example,
use the following code:

#include <iostream>
using namespace std;

mai n()
{
int m, n, k;

cout « "\nEnter two integers:";


ci n » m » n;
k = im + n;
cout « "\nTheir sum is "« k «
}
3. Write a program that converts distances measured in yards to distances mea¬
sured in meters. The relationship is 1 meter equals 1.0936 yards. Write the pro¬
gram to use ci n to read in distances. The program should be a loop that does
this calculation until it receives 0 or a negative number for input. In the previ¬
ous exercise, we used cin and the overloaded operator >>, which together
replace scanf() in C. For example, cin >> v is the C++ equivalent to
scanf ("%fype" , &v). See Section D.4, “The Input Class i stream,” on page 420,
for more information on input in C++.

4. Write a program that interactively asks for your name and age and responds
with

Hello name, next year you will be next_age.

where next_age is age + 1.

5. Write a program that prints out a table of squares, square roots, and cubes. Use
either tabbing or strings of blanks to get a neatly aligned table.

i i * i square root i * i * i

1 1 1.00000 1
▼ Exercises 21

6. Write a class person that contains basic information, such as name, birthdate,
and address. Derive class student from class person. (See Section 1.7,
“Inheritance,” on page 12.)

/. (S. damage) The following three programs behave differently. We start with

//Function declarations at file scope

int f(int):

double f(double); //overloads f(int) double add f()

return(f(l) + f(1.0)); //f(int) + f(double)


}

We place one function declaration internally.

//Function declaration at local scope

int f(int);
double add f()
{
double f(double) ; //hides f(int)
return(f(l) + f(1.0)); //f(double) + f(double)
}
Now we place the other function declaration internally.

double f(double);
double add f()
{
i nt f (i nt) ;
return(f(l) + f(1.0)); //What is called here?
}
Write some test programs that clearly show the different behaviors.
.

'
Chapter 2
Native Types
and Statements
This chapter, together with Chapter 3, “Functions, Pointers, and Arrays,” will pro¬
vide an introduction to programming in C++ using its native types and its nonOOP
features. Since C++ is based on the C language, much of this material is a review of
C. A native type is one provided by the language directly. In C++, this includes the
simple types, such as character types, integer types, floating-point types, and the
boolean type, as well as derived types, such as array types, pointer types, and struc¬
ture types, which are aggregates of the simple types. This chapter focuses on the
native simple data types and statements.
The intent of this chapter, Chapter 3, “Functions, Pointers, and Arrays,” and
parts of Chapter 4, “Classes,” is to enable programmers to program in that subset of
C++ that approximates a traditional imperative language, such as C, Pascal, or
FORTRAN. This subset is what we are calling the kernel language. The improve¬
ments to C in the kernel language of C++ are useful enough to prefer C++ over C,
even for traditional programming. These enhancements lead to C++ as a better C,
independent of the more extensive additional object-oriented features. These chap¬
ters also contain examples that will be used throughout the book.
An important feature of OOP is type extensibility, or the ability within the pro¬
gramming language to develop new types suitable to a problem domain. For this
extensibility to work properly, the new type should work like the native types of the
kernel language. Object-oriented design of user-defined types should mimic the
look and feel of the native types.
For the experienced C programmer, most of this chapter’s material should be
skimmed and read mainly with an eye for differences between C and C++. These dif¬
ferences will be listed in the chapter summary, which the experienced C program¬
mer can use to determine what to selectively read about. For a programmer coming
from another language, such as Java or Pascal, or for some C programmers needing
a review of C material, this chapter and the next two succinctly review the C++ ker¬
nel language.
Exploring the Variety of Random
Documents with Different Content
IV
Always a little lonely, lost in the ceaseless unfolding of his
mysticism, old Andrew Pengilly had been the lonelier since Frank
Shallard had left him.
When he heard that the Reverend Elmer Gantry was coming, Mr.
Pengilly murmured to the local committee that it would be a pleasure
to put up Mr. Gantry and save him from the scurfy village hotel.
He had read of Mr. Gantry as an impressive orator, a courageous
fighter against Sin. Mr. Pengilly sighed. Himself, somehow, he had
never been able to find so very much Sin about. His fault. A silly old
dreamer. He rejoiced that he, the mousy village curé, was about to
have here, glorifying his cottage, a St. Michael in dazzling armor.

V
After the evening Chautauqua Elmer sat in Mr. Pengilly’s hovel,
and he was graciously condescending.
“You say, Brother Pengilly, that you’ve heard of our work at
Wellspring? But do we get so near the hearts of the weak and
unfortunate as you here? Oh, no; sometimes I think that my first
pastorate, in a town smaller than this, was in many ways more
blessed than our tremendous to-do in the great city. And what is
accomplished there is no credit to me. I have such splendid, such
touchingly loyal assistants—Mr. Webster, the assistant pastor—such
a consecrated worker, and yet right on the job—and Mr. Wink, and
Miss Weezeger, the deaconess, and dear Miss Bundle, the secretary
—such a faithful soul, so industrious. Oh, yes, I am singularly
blessed! But, uh, but— Given these people, who really do the work,
we’ve been able to put over some pretty good things—with God’s
leading. Why, say, we’ve started the only class in show-window
dressing in any church in the United States—and I should suppose
England and France! We’ve already seen the most wonderful
results, not only in raising the salary of several of the fine young men
in our church, but in increasing business throughout the city and
improving the appearance of show-windows, and you know how
much that adds to the beauty of the down-town streets! And the
crowds do seem to be increasing steadily. We had over eleven
hundred present on my last Sunday evening in Zenith, and that in
summer! And during the season we often have nearly eighteen
hundred, in an auditorium that’s only supposed to seat sixteen
hundred! And with all modesty—it’s not my doing but the methods
we’re working up—I think I may say that every man, woman, and
child goes away happy and yet with a message to sustain ’em
through the week. You see—oh, of course I give ’em the straight old-
time gospel in my sermon—I’m not the least bit afraid of talking right
up to ’em and reminding them of the awful consequences of sin and
ignorance and spiritual sloth. Yes, sir! No blinking the horrors of the
old-time proven Hell, not in any church I’m running! But also we
make ’em get together, and their pastor is just one of their own
chums, and we sing cheerful, comforting songs, and do they like it?
Say! It shows up in the collections!”
“Mr. Gantry,” said Andrew Pengilly, “why don’t you believe in
God?”
CHAPTER XXVIII

his friendship with Dr. Philip McGarry of the Arbor Church was
all, Frank Shallard felt, that kept him in the church. As to his round
little wife Bess and the three respectable children, he had for them
less passion than compassion, and he could, he supposed, make
enough money somehow to care for them.
McGarry was not an extraordinary scholar, not especially
eloquent, not remarkably virtuous, but in him there was kindness
along with robust humor, a yearning for justice steeled by common
sense, and just that quality of authentic good-fellowship which the
Professional Good Fellows of Zenith, whether preachers or shoe-
salesmen, blasphemed against by shouting and guffawing and back-
slapping. Women trusted in his strength and his honor; children were
bold with him; men disclosed to him their veiled sorrows; and he was
more nimble to help them than to be shocked.
Frank worshiped him.
Himself a bachelor, McGarry had become an intimate of Frank’s
house. He knew where the ice-pick was kept, and where the thermos
bottles for picnics; he was as likely as Frank to wash up after late
suppers; and if he called and the elder Shallards were not in, he
slipped up-stairs and was found there scandalously keeping the
children awake by stories of his hunting in Montana and Arizona and
Saskatchewan.
It was thus when Frank and Bess came home from prayer-
meeting one evening. Philip McGarry’s own prayer-meetings were
brief. A good many people said they were as artificial a form of
religious bait as Elmer Gantry’s Lively Sunday Evenings, but if
McGarry did also have the habit of making people sing “Smile,
Smile, Smile” on all public events except possibly funerals, at least
he was not so insistent about their shouting it.
They drifted down to the parsonage living-room, which Bess had
made gay with chintzes, Frank studious with portentous books of
sociology. Frank sat deep in a chair smoking a pipe—he could never
quite get over looking like a youngish college professor who smokes
to show what a manly fellow he is. McGarry wandered about the
room. He had a way of pointing arguments by shaking objects of
furniture—pokers, vases, books, lamps—which was as dangerous
as it looked.
“Oh, I was rotten at prayer-meeting tonight,” Frank grumbled.
“Darn it, I can’t seem to go on being interested in the fact that old
Mrs. Besom finds God such a comfort in her trials. Mrs. Besom’s
daughter-in-law doesn’t find Mrs. Besom any comfort in her trials, let
me tell you! And yet I don’t see how I can say to her, after she’s been
fluttering around among the angels and advertising how dead certain
she is that Jesus loves her—I haven’t quite the nerve to say, ‘Sister,
you tight-fisted, poison-tongued, old hellcat—’ ”
“Why, Frank!” from Bess, in placid piety.
“ ‘—you go home and forget your popularity in Heaven and ask
your son and his wife to forgive you for trying to make them your kind
of saint, with acidity of the spiritual stomach!’ ”
“Why, Frank!”
“Let him rave, Bess,” said McGarry. “If a preacher didn’t cuss his
congregation out once in a while, nobody but St. John would ever’ve
lasted—and I’ll bet he wasn’t very good at weekly services and
parish visiting!”
“And,” went on Frank, “tomorrow I’ve got a funeral. That Henry
Semp. Weighed two hundred and eighty pounds from the neck down
and three ounces from the neck up. Perfectly good Christian citizen
who believed that Warren G. Harding was the greatest man since
George Washington. I’m sure he never beat his wife. Worthy
communicant. But when his wife came to hire me, she wept like the
dickens when she talked about Henry’s death, but I noticed from the
window that when she went off down the street she looked
particularly cheerful. Yes, Henry was a bulwark of the nation; not to
be sneered at by highbrows. And I’m dead certain, from something
she said, that every year they’ve jipped the Government out of every
cent they could on their income tax. And tomorrow I’m supposed to
stand up there and tell his friends what a moral example and
intellectual Titan he was, and how the poor little woman is simply
broken by sorrow. Well, cheer up! From what I know of her, she’ll be
married again within six months, and if I do a good job of priesting
tomorrow, maybe I’ll get the fee! Oh, Lord, Phil, what a job, what a
lying compromising job, this being a minister!”
It was their hundredth argument over the question.
McGarry waved a pillow, discarded it for Bess’ purse, while she
tried not to look alarmed, and shouted, “It is not! As I heard a big
New York preacher say one day: he knew how imperfect the ministry
is, and how many second-raters get into it, and yet if he had a
thousand lives, he’d want to be a minister of the gospel, to be a man
showing the philosophy of Jesus to mankind, in every one of ’em.
And the church universal, no matter what its failings, is still the only
institution in which we can work together to hand on that gospel.
Maybe it’s your fault, not the church’s, young Frank, if you’re so
scared of your people that you lie at funerals! I don’t, by Jiminy!”
“You do, by Jiminy, my dear Phil! You don’t know it. No, what you
do is, you hypnotize yourself until you’re convinced that every dear
departed was a model of some virtue, and then you rhapsodize
about that.”
“Well, probably he was!”
“Of course. Probably your burglar was a model of courage, and
your gambler a model of kindness to everybody except the people
he robbed, but I don’t like being hired to praise burglars and
gamblers and respectable loan-sharks and food-hounds like Henry
Semp, and encourage youngsters to accept their standards, and so
keep on perpetuating this barbarous civilization for which we
preachers are as responsible as the lawyers or the politicians or the
soldiers or even the school-masters. No, sir! Oh, I am going to get
out of the church! Think of it! A preacher, getting religion, getting
saved, getting honest, getting out! Then I’d know the joys of
sanctification that you Methodys talk about!”
“Oh, you make me tired!” Bess complained, not very
aggressively. She looked, at forty-one, like a plump and amiable girl
of twenty. “Honestly, Phil, I do wish you could show Frank where he’s
wrong. I can’t, and I’ve been trying these fifteen years.”
“You have, my lamb!”
“Honestly, Phil, can’t you make him see it?” said Bess. “He’s—of
course I do adore him, but of all the cry-babies I ever met— He’s the
worst of all my children! He talks about going into charity work, about
getting a job with a labor bank or a labor paper, about lecturing,
about trying to write. Can’t you make him see that he’d be just as
discontented whatever he did? I’ll bet you the labor leaders and
radical agitators and the Charity Organization Society people aren’t
perfect little angels any more than preachers are!”
“Heavens, I don’t expect ’em to be! I don’t expect to be content,”
Frank protested. “And isn’t it a good thing to have a few people who
are always yammering? Never get anywhere without. What a joke
that a minister, who’s supposed to have such divine authority that he
can threaten people with hell, is also supposed to be such an office-
boy that he can be cussed out and fired if he dares to criticize
capitalists or his fellow ministers! Anyway— Dear Bess, it’s rotten on
you. I’d like to be a contented sort, I’d like to ‘succeed,’ to be
satisfied with being half-honest. But I can’t. . . . You see, Phil, I was
brought up to believe the Christian God wasn’t a scared and
compromising public servant, but the creator and advocate of the
whole merciless truth, and I reckon that training spoiled me—I
actually took my teachers seriously!”
“Oh, tut, tut, Frank; trouble with you is,” Philip McGarry yawned,
“trouble with you is, you like arguing more than you do patiently
working out the spiritual problems of some poor, dumm, infinitely
piteous human being that comes to you for help, and that doesn’t
care a hoot whether you advocate Zoroastrianism or Seventh-day
Adventism, so long as he feels that you love him and that you can
bring him strength from a power higher than himself. I know that if
you could lose your intellectual pride, if you could forget that you
have to make a new world, better’n the Creator’s, right away tonight
—you and Bernard Shaw and H. G. Wells and H. L. Mencken and
Sinclair Lewis (Lord, how that book of Lewis’, ‘Main Street,’ did bore
me, as much of it as I read; it just rambled on forever, and all he
could see was that some of the Gopher Prairie hicks didn’t go to
literary teas quite as often as he does!—that was all he could see
among those splendid heroic pioneers)! Well, as I was saying, if
instead of starting in where your congregation has left off, because
they never had your chance, you could draw them along with you—”
“I try to! And let me tell you, young fellow, I’ve got a few of ’em far
enough along so they’re having the sense to leave me and my
evangelical church and go off to the Unitarians or stay away from
church altogether—thus, Bess darling, depriving my wife and babes
of a few more pennies! But seriously, Phil—”
“A man always says ‘But seriously’ when he feels the previous
arguments haven’t been so good yet!”
“Maybe. But anyway, what I mean to say is: Of course my
liberalism is all foolishness! Do you know why my people stand for
it? They’re not enough interested to realize what I’m saying! If I had
a successor who was a fundamentalist, they’d like him just as well or
better, and they’d go back a-whooping to the sacred hell-fire that I’ve
coaxed ’em out of. They don’t believe I mean it when I take a shot at
the fear of eternal punishment, and the whole magic and taboo
system of worshiping the Bible and the ministry, and all the other
skull-decorated vestiges of horror there are in so-called Christianity!
They don’t know it! Partly it’s because they’ve been trained not to
believe anything much they hear in sermons. But also it’s my fault.
I’m not aggressive. I ought to jump around like a lunatic or a popular
evangelist, and shout, ‘D’ you understand? When I say that most of
your religious opinions are bunk, why, what I mean is, they’re bunk!’
I’ve never been violently enough in earnest to be beaten for the sake
of the Lord our God! . . . Not yet!”
“Hah, there I’ve got you, Frank! Tickles me to see you try to be
the village atheist! ‘For the sake of the Lord’ you just said. And how
often I’ve heard you say at parting ‘God bless you’—and you meant
it! Oh, no, you don’t believe in Christ! Not any more than the Pope at
Rome!”
“I suppose that if I said ‘God damn you,’ that would also prove
that I was a devout Christian! Oh, Phil, I can’t understand how a man
as honest as you, as really fond of helping people—and of tolerating
them!—can stand being classed with a lot of your fellow preachers
and not even kick about it! Think of your going on enduring being a
fellow Methodist preacher right in the same town with Elmer Gantry
and not standing up in ministers’ meeting and saying, ‘Either he gets
out or I do!’ ”
“I know! You idiot, don’t you suppose those of us that are halfway
decent suffer from being classed with Gantry, and that we hate him
more than you do? But even if Elmer is rather on the swine side,
what of it? Would you condemn a fine aspiring institution, full of
broad-gauged, earnest fellows, because one of them was a wash-
out?”
“One? Just one? I’ll admit there aren’t many, not very many, hogs
like Gantry in your church, or any other, but let me give my loving
fraternal opinions of a few others of your splendid Methodist fellows!
Bishop Toomis is a gas-bag. Chester Brown, with his candles and
chanting, he’s merely an Episcopalian who’d go over to the
Episcopal church if he weren’t afraid he’d lose too much salary in
starting again—just as a good share of the Anglo-Catholic
Episcopalians are merely Catholics who’d go over to Rome if they
weren’t afraid of losing social caste. Otto Hickenlooper, with his
institutions—the rich are so moved by his charities that they hand
him money and Otto gets praised for spending that money. Fine
vicious circle. And think of some poor young idiot studying art,
wasting his time and twisting his ideas, at Otto’s strictly moral art
class, where the teacher is chosen more for his opinions on the
sacraments than for his knowledge of composition.”
“But, Frank, I’ve said all—”
“And the sound, the scholarly, the well-balanced Dr. Mahlon
Potts! Oh, he’s a perfectly good man, and not a fanatic. Doesn’t
believe that evolution is a fiendish doctrine. The only trouble with him
—as with most famous preachers—is that he hasn’t the slightest
notion what human beings are like. He’s insulated; has been ever
since he became a preacher. He goes to the death-beds of
prostitutes (but not very often, I’ll bet!) but he can’t understand that
perfectly decent husbands and wives often can’t get along because
of sexual incompatibility.
“Potts lives in a library; he gets his idea of human motives out of
George Eliot and Margaret Deland, and his ideas of economics out
of editorials in the Advocate, and his idea as to what he really is
accomplishing out of the flattery of his Ladies’ Aid! He’s a much
worse criminal than Gantry! I imagine Elmer has some desire to be a
good fellow and share his swag, but Dr. Potts wants to make over an
entire world of living, bleeding, sweating, loving, fighting human
beings into the likeness of Dr. Potts—of Dr. Potts taking his
afternoon nap and snoring under a shelf of books about the
doctrines of the Ante-Nicene Fathers!”
“Golly, you simply love us! And I suppose you think I admire all
these fellows! Why, they regard me as a heretic, from the bishop
down,” said Philip McGarry.
“And yet you stay with them!”
“Any other church better?”
“Oh, no. Don’t think I give all my love to the Methodists. I take
them only because they’re your particular breed. My own
Congregationalists, the Baptists who taught me that immersion is
more important than social justice, the Presbyterians, the
Campbellites, the whole lot—oh, I love ’em all about equally!”
“And what about yourself? What about me?”
“You know what I think of myself—a man too feeble to stand up
and risk being called a crank or a vile atheist! And about you, my
young liberal friend, I was just saving you to the last in my exhibit of
Methodist parsons! You’re the worst of the lot!”
“Oh, now, Frank!” yawned Bess.
She was sleepy. How preachers did talk! Did plasterers and
authors and stock-brokers sit up half the night discussing their souls,
fretting as to whether plastering or authorship or stock-broking was
worth while?
She yawned again, kissed Frank, patted Philip’s cheek, and
made exit with, “You may be feeble, Frank, but you certainly can talk
a strong, rugged young wife to death!”
Frank, usually to be cowed by her jocose grumbling and Philip’s
friendly jabs, was tonight afire and unquenchable.
“Yes, you’re the worst of all, Phil! You do know something of
human beings. You’re not like old Potts, who’s always so informative
about how much sin there is in the world and always so astonished
when he meets an actual sinner. And you don’t think it matters a
hang whether a seeker after decency gets ducked—otherwise
baptized—or not. And yet when you get up in the pulpit, from the
way you wallow in prayer people believe that you’re just as chummy
with the Deity as Potts or Gantry. Your liberalism never lasts you
more than from my house to the street-car. You talk about the golden
streets of Heaven and the blessed peace of the hereafter, and yet
you’ve admitted to me, time and again, that you haven’t the slightest
idea whether there is any personal life after death. You talk about
Redemption, and the Sacrament of the Lord’s Supper, and how God
helps this nation to win a war and hits that other with a flood, and a
lot more things that you don’t believe privately at all.”
“Oh, I know! Thunder! But you yourself—you pray in church.”
“Not really. For over a year now I’ve never addressed a prayer to
any definite deity. I say something like ‘Let us in meditation,
forgetting the worries of daily life, join our spirits in longing for the
coming of perpetual peace’—something like that.”
“Well, it sounds like a pretty punk prayer to me, Frankie! The only
trouble with you is, you feel you’re called on to re-write the Lord’s
Prayer for him!”
Philip laughed gustily, and slapped Frank’s shoulder.
“Damn it, don’t be so jocular! I know it’s a poor prayer. It’s terrible.
Nebulous. Meaningless. Like a barker at the New Thought side-
show. I don’t mind your disliking it, but I do mind your trying to be
humorous! Why is it that you lads who defend the church are so
facetious when you really get down to discussing the roots of
religion?”
“I know, Frank. Effect of too much preaching. But seriously: Yes, I
do say things in the pulpit that I don’t mean literally. What of it?
People understand these symbols; they’ve been brought up with
them, they’re comfortable with them. My object in preaching is to
teach the art of living as far as I can; to encourage my people—and
myself—to be kind, to be honest, to be clean, to be courageous, to
love God and their fellow-men; and the whole experience of the
church shows that those lessons can best be taught through such
really noble concepts as salvation and the presence of the Holy
Ghost and Heaven and so on.”
“Hm. Does it? Has the church ever tried anything else? And just
what the dickens do you mean by ‘being clean’ and ‘being honest’
and ‘teaching the art of living’? Lord, how we preachers do love to
use phrases that don’t mean anything! But suppose you were
perfectly right. Nevertheless, by using the same theological slang as
a Gantry or a Toomis or a Potts, you unconsciously make everybody
believe that you think and act like them too.”
“Nonsense! Not that I’m particularly drawn by the charms of any
of these fellow sages. I’d rather be wrecked on a desert island with
you, you old atheist!—you darned old fool! But suppose they were as
bad as you think. I still wouldn’t feel it was my duty to foul my own
nest, to make this grand old Methodist Church, with its saints and
heroes like Wesley and Asbury and Quayle and Cartwright and
McDowell and McConnell—why, the tears almost come to my eyes
when I think of men like that! Look here: Suppose you were at war, in
a famous regiment. Suppose a lot of your fellow soldiers, even the
present commander of the regiment himself, were rotters—cowards.
Would you feel called on to desert? Or to fight all the harder to make
up for their faults?”
“Phil, next to the humorous ragging I spoke of, and the use of
stale phrases, the worst cancer in religious discussion is the use of
the metaphor! The Protestant church is not a regiment. You’re not a
soldier. The soldier has to fight when and as he’s told. You have
absolute liberty, outside of a few moral and doctrinal compulsions.”
“Ah-hah, now I’ve got you, my logical young friend! If we have
that liberty, why aren’t you willing to stay in the church? Oh, Frank,
Frank, you are such a fool! I know that you long for righteousness.
Can’t you see that you can get it best by staying in the church,
liberalizing from within, instead of running away and leaving the
people to the ministrations of the Gantrys?”
“I know. I’ve been thinking just that all these years. That’s why I’m
still a preacher! But I’m coming to believe that it’s tommyrot. I’m
coming to think that the hell-howling old mossbacks corrupt the
honest liberals a lot more than the liberals lighten the backwoods
minds of the fundamentalists. What the dickens is the church
accomplishing, really? Why have a church at all? What has it for
humanity that you won’t find in worldly sources—schools, books,
conversation?”
“It has this, Frank: It has the unique personality and teachings of
Jesus Christ, and there is something in Jesus, there is something in
the way he spoke, there is something in the feeling of a man when
he suddenly has that inexpressible experience of knowing the
Master and his presence, which makes the church of Jesus different
from any other merely human institution or instrument whatsoever!
Jesus is not simply greater and wiser than Socrates or Voltaire; he is
entirely different. Anybody can interpret and teach Socrates or
Voltaire—in schools or books or conversation. But to interpret the
personality and teachings of Jesus requires an especially called,
chosen, trained, consecrated body of men, united in an especial
institution—the church.”
“Phil, it sounds so splendid. But just what were the personality
and the teachings of Jesus? I’ll admit it’s the heart of the controversy
over the Christian religion:—aside from the fact that, of course, most
people believe in a church because they were born to it. But the
essential query is: Did Jesus—if the Biblical accounts of him are
even half accurate—have a particularly noble personality, and were
his teachings particularly original and profound? You know it’s almost
impossible to get people to read the Bible honestly. They’ve been so
brought up to take the church interpretation of every word that they
read into it whatever they’ve been taught to find there. It’s been so
with me, up to the last couple of years. But now I’m becoming a
quarter free, and I’m appalled to see that I don’t find Jesus an
especially admirable character!
“He is picturesque. He tells splendid stories. He’s a good fellow,
fond of low company—in fact the idea of Jesus, whom the bishops of
his day cursed as a rounder and wine-bibber, being chosen as the
god of the Prohibitionists is one of the funniest twists in history. But
he’s vain, he praises himself outrageously, he’s fond of astonishing
people by little magical tricks which we’ve been taught to revere as
‘miracles.’ He is furious as a child in a tantrum when people don’t
recognize him as a great leader. He loses his temper. He blasts the
poor barren fig-tree when it doesn’t feed him. What minds people
have! They hear preachers proving by the Bible the exact opposites,
that the Roman Catholic Church is divinely ordained and that it is
against all divine ordinances, and it never occurs to them that far
from the Christian religion—or any other religion—being a blessing
to humanity, it’s produced such confusion in all thinking, such
secondhand viewing of actualities, that only now are we beginning to
ask what and why we are, and what we can do with life!
“Just what are the teachings of Christ? Did he come to bring
peace or more war? He says both. Did he approve earthly
monarchies or rebel against them? He says both. Did he ever—think
of it, God himself, taking on human form to help the earth—did he
ever suggest sanitation, which would have saved millions from
plagues? And you can’t say his failure there was because he was
too lofty to consider mere sickness. On the contrary, he was awfully
interested in it, always healing some one—providing they flattered
his vanity enough!
“What did he teach? One place in the Sermon on the Mount he
advises—let me get my Bible—here it is: ‘Let your light so shine
before men that they may see your good works and glorify your
Father which is in heaven,’ and then five minutes later he’s saying,
‘Take heed that ye do not your alms before men, to be seen of them,
otherwise ye have no reward of your Father which is in heaven.’
That’s an absolute contradiction, in the one document which is the
charter of the whole Christian Church. Oh, I know you can reconcile
them, Phil. That’s the whole aim of the ministerial training: to teach
us to reconcile contradictions by saying that one of them doesn’t
mean what it means—and it’s always a good stunt to throw in ‘You’d
understand it if you’d only read it in the original Greek’!
“There’s just one thing that does stand out clearly and
uncontradicted in Jesus’ teaching. He advocated a system of
economics whereby no one saved money or stored up wheat or did
anything but live like a tramp. If this teaching of his had been
accepted, the world would have starved in twenty years after his
death!
“No, wait, Phil, just one second and then I’m through!”
He talked till dawn.
Frank’s last protest, as they stood on the steps in the cold
grayness, was:
“My objection to the church isn’t that the preachers are cruel,
hypocritical, actually wicked, though some of them are that, too—
think of how many are arrested for selling fake stock, for seducing
fourteen-year-old girls in orphanages under their care, for arson, for
murder. And it isn’t so much that the church is in bondage to Big
Business and doctrines as laid down by millionaires—though a lot of
churches are that, too. My chief objection is that ninety-nine per cent.
of sermons and Sunday School teachings are so agonizingly dull!”
CHAPTER XXIX

I
however impatient he was with Frank, Philip McGarry’s last wish
was to set Elmer Gantry piously baying on Frank’s trail. It was rather
an accident. Philip sat next to Elmer at a dinner to discuss
missionary funds; he remembered that Frank and Elmer had been
classmates; and with a sincerely affectionate “It’s too bad the poor
boy worries so over what are really matters for Faith,” he gave away
to Elmer most of Frank’s heresies.
Now in the bustle of raising funds to build a vast new church,
Elmer had forgotten his notion of saving the renowned hardware
impresario, Mr. William Dollinger Styles, and his millions from
contamination by Frank’s blasphemies.
“We could use old Styles, and you could get some fine publicity
by attacking Shallard’s attempt to steal Jesus and even Hell away
from us,” said Elmer’s confidant, Mr. T. J. Rigg, when he was
consulted.
“Say, that’s great. How liberalism leads to atheism. Fine! Wait till
Mr. Frank Shallard opens his mouth and puts his foot in it again!”
said the Reverend Elmer Gantry. “Say, I wonder how we could get a
report of his sermons? The poor fish isn’t important enough so’s they
very often report his junk in the papers.”
“I’ll take care of that. I’ve got a girl in my office, good fast worker,
that I’ll have go and take down all his sermons. They’ll just think
she’s practising stenography.”
“Well, by golly, that’s one good use for sermons. Ha, ha, ha!” said
Elmer.
“Yes, sir, by golly, found at last. Ha, ha, ha!” said Mr. T. J. Rigg.

II
In less than a month Frank maddened the citizens of Zenith by
asserting, in the pulpit, that though he was in favor of temperance,
he was not for Prohibition; that the methods of the Anti-Saloon
League were those of a lumber lobby.
Elmer had his chance.
He advertised that he would speak on “Fake Preachers—and
Who They Are.”
In his sermon he said that Frank Shallard (by name) was a liar, a
fool, an ingrate whom he had tried to help in seminary, a thief who
was trying to steal Christ from an ailing world.
The newspapers were pleased and explicit.
Elmer saw to it—T. J. Rigg arranged a foursome—that he played
golf with William Dollinger Styles that week.
“I was awfully sorry, Mr. Styles,” he said, “to feel it my duty to
jump on your pastor, Mr. Shallard, last Sunday, but when a fellow
stands up and makes fun of Jesus Christ—well, it’s time to forget
mercy!”
“I thought you were kind of hard on him. I didn’t hear his sermon
myself—I’m a church-member, but it does seem like things pile up so
at the office that I have to spend almost every Sunday morning
there. But from what they’ve told me, he wasn’t so wild.”
“Then you don’t think Shallard is practically an atheist?”
“Why, no! Nice decent fellow—”
“Mr. Styles, do you realize that all over town people are
wondering how a man like you can give his support to a man like
Shallard? Do you realize that not only the ministers but also laymen
are saying that Shallard is secretly both an agnostic and a socialist,
though he’s afraid to come out and admit it? I hear it everywhere.
People are afraid to tell you. Jiminy, I’m kind of scared of you myself!
Feel I’ve got a lot of nerve!”
“Well, I ain’t so fierce,” said Mr. Styles, very pleased.
“Anyway, I’d hate to have you think I was sneaking around
damning Shallard behind his back. Why don’t you do this? You and
some of the other Dorchester deacons have Shallard for lunch or
dinner, and have me there, and let me put a few questions to him. I’ll
talk to the fellow straight! Do you feel you can afford to be known as
tolerating an infidel in your church? Oughtn’t you to make him come
out from under cover and admit what he thinks? If I’m wrong, I’ll
apologize to you and to him, and you can call me all the kinds of
nosey, meddling, cranky, interfering fool you want to!”
“Well—— He seems kind of a nice fellow.” Mr. Styles was
uncomfortable. “But if you’re right about him being really an infidel,
don’t know’s I could stand that.”
“How’d it be if you and some of your deacons and Shallard came
and had dinner with me in a private room at the Athletic Club next
Friday evening?”
“Well, all right—”

III
Frank was so simple as to lose his temper when Elmer had
bullied him, roared at him, bulked at him, long enough, with Frank’s
own deacons accepting Elmer as an authority. He was irritated out of
all caution, and he screamed back at Elmer that he did not accept
Jesus Christ as divine; that he was not sure of a future life; that he
wasn’t even certain of a personal God.
Mr. William Dollinger Styles snapped, “Then just why, Mr.
Shallard, don’t you get out of the ministry before you’re kicked out?”
“Because I’m not yet sure—— Though I do think our present
churches are as absurd as a belief in witchcraft, yet I believe there
could be a church free of superstition, helpful to the needy, and
giving people that mystic something stronger than reason, that sense
of being uplifted in common worship of an unknowable power for
good. Myself, I’d be lonely with nothing but bleak debating-societies.
I think—at least I still think—that for many souls there is this need of
worship, even of beautiful ceremonial—”
“ ‘Mystic need of worship!’ ‘Unknowable power for good!’ Words,
words, words! Milk and water! That, when you have the glorious and
certain figure of Christ Jesus to worship and follow!” bellowed Elmer.
“Pardon me, gentlemen, for intruding, but it makes me, not as a
preacher but just as a humble and devout Christian, sick to my
stomach to hear a fellow feel that he knows so blame’ much he’s
able to throw out of the window the Christ that the whole civilized
world has believed in for countless centuries! And try to replace him
with a lot of gassy phrases! Excuse me, Mr. Styles, but after all,
religion is a serious business, and if we’re going to call ourselves
Christians at all, we have to bear testimony to the proven fact of
God. Forgive me.”
“It’s quite all right, Dr. Gantry. I know just how you feel,” said
Styles. “And while I’m no authority on religion, I feel the same way
you do, and I guess these other gentlemen do, too. . . . Now,
Shallard, you’re entitled to your own views, but not in our pulpit! Why
don’t you just resign before we kick you out?”
“You can’t kick me out! It takes the whole church to do that!”
“The whole church’ll damn well do it, you watch ’em!” said
Deacon William Dollinger Styles.

IV
“What are we going to do, dear?” Bess said wearily. “I’ll stand by
you, of course, but let’s be practical. Don’t you think it would make
less trouble if you did resign?”
“I’ve done nothing for which to resign! I’ve led a thoroughly
decent life. I haven’t lied or been indecent or stolen. I’ve preached
imagination, happiness, justice, seeking for the truth. I’m no sage,
Heaven knows, but I’ve given my people a knowledge that there are
such things as ethnology and biology, that there are books like
‘Ethan Frome’ and ‘Père Goriot’ and ‘Tono-Bungay’ and Renan’s
Jesus, that there is nothing wicked in looking straight at life—”
“Dear, I said practical!”
“Oh, thunder, I don’t know. I think I can get a job in the Charity
Organization Society here—the general secretary happens to be
pretty liberal.”
“I hate to have us leave the church entirely. I’m sort of at home
there. Why not see if they’d like to have you in the Unitarian
Church?”
“Too respectable. Scared. Same old sanctified phrases I’m trying
to get rid of—and won’t ever quite get rid of, I’m afraid.”

V
A meeting of the church body had been called to decide on
Frank’s worthiness, and the members had been informed by Styles
that Frank was attacking all religion. Instantly a number of the
adherents who had been quite unalarmed by what they themselves
had heard in the pulpit perceived that Frank was a dangerous fellow
and more than likely to injure omnipotent God.
Before the meeting, one woman, who remained fond of him,
fretted to Frank, “Oh, can’t you understand what a dreadful thing
you’re doing to question the divinity of Christ and all? I’m afraid
you’re going to hurt religion permanently. If you could open your
eyes and see—if you could only understand what my religion has
meant to me in times of despair! I don’t know what I would have
done during my typhoid without that consolation! You’re a bright,
smart man when you let yourself be. If you’d only go and have a
good talk with Dr. G. Prosper Edwards. He’s an older man than you,
and he’s a doctor of divinity, and he has such huge crowds at Pilgrim
Church, and I’m sure he could show you where you’re wrong and
make everything perfectly clear to you.”
Frank’s sister, married now to an Akron lawyer, came to stay with
them. They had been happy, Frank and she, in the tepid but amiable
house of their minister-father; they had played at church, with dolls
and salt-cellars for congregation; books were always about them,
natural to them; and at their father’s table they had heard doctors,
preachers, lawyers, politicians, talk of high matters.
The sister bubbled to Bess, “You know, Frank doesn’t believe half
he says! He just likes to show off. He’s a real good Christian at heart,
if he only knew it. Why, he was such a good Christian boy—he led
the B. Y. P. U.—he couldn’t have drifted away from Christ into all this
nonsense that nobody takes seriously except a lot of long-haired
dirty cranks! And he’ll break his father’s heart! I’m going to have a
good talk with that young man, and bring him to his senses!”
On the street Frank met the great Dr. McTiger, pastor of the
Royal Ridge Presbyterian Church.
Dr. McTiger had been born in Scotland, graduated at Edinburgh,
and he secretly—not too secretly—despised all American
universities and seminaries and their alumni. He was a large,
impatient, brusque man, renowned for the length of his sermons.
“I hear, young man,” he shouted at Frank, “that you have read
one whole book on the pre-Christian mysteries and decided that our
doctrines are secondhand and that you are now going to destroy the
church. You should have more pity! With the loss of a profound
intellect like yours, my young friend, I should doubt if the church can
stagger on! It’s a pity that after discovering scholarship you didn’t go
on and get enough of that same scholarship to perceive that by the
wondrous beneficence of God’s mercy the early church was led to
combine many alien factors in the one perfection of the Christian
brotherhood! I don’t know whether it’s ignorance of church history or
lack of humor that chiefly distinguishes you, my young friend! Go and
sin no more!”
From Andrew Pengilly came a scrawled, shaky letter begging
Frank to stand true and not deliver his appointed flock to the devil.
That hurt.

VI
The first church business meeting did not settle the question of
Frank’s remaining. He was questioned about his doctrines, and he
shocked them by being candid, but the men whom he had helped,
the women whom he had consoled in sickness, the fathers who had
gone to him when their daughters “had gotten into trouble,” stood by
him for all the threats of Styles.
A second meeting would have to be called before they took a
vote.
When Elmer read of this, he galloped to T. J. Rigg. “Here’s our
chance!” he gloated. “If the first meeting had kicked Frank out, Styles
might have stayed with their church, though I do think he likes my
brand of theology and my Republican politics. But why don’t you go

You might also like