100% found this document useful (3 votes)
12 views

Object Oriented Programming Using C An Introduction 1st Edition by Pardoe, King 0333692411 978-0333692417instant download

The document is a comprehensive guide to Object Oriented Programming using C++, aimed at beginners with no prior programming experience. It covers fundamental programming concepts, object-oriented principles, and the C++ language features through straightforward examples and exercises. The book emphasizes the importance of understanding basic concepts before advancing to more complex topics in software development.

Uploaded by

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

Object Oriented Programming Using C An Introduction 1st Edition by Pardoe, King 0333692411 978-0333692417instant download

The document is a comprehensive guide to Object Oriented Programming using C++, aimed at beginners with no prior programming experience. It covers fundamental programming concepts, object-oriented principles, and the C++ language features through straightforward examples and exercises. The book emphasizes the importance of understanding basic concepts before advancing to more complex topics in software development.

Uploaded by

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

Object Oriented Programming Using C An

Introduction 1st Edition by Pardoe, King


0333692411 978-0333692417 download

https://ebookball.com/product/object-oriented-programming-using-
c-an-introduction-1st-edition-by-pardoe-
king-0333692411-978-0333692417-15282/

Instantly Access and Download Textbook at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Object Oriented Programming using C 1st Edition by Simon Kendal


9788776818142

https://ebookball.com/product/object-oriented-programming-
using-c-1st-edition-by-simon-kendal-9788776818142-15260/

Beginning C 3 0 an introduction to object oriented programming 1st


edition by Jack Purdum 0470261293 978-0470261293

https://ebookball.com/product/beginning-c-3-0-an-introduction-to-
object-oriented-programming-1st-edition-by-jack-
purdum-0470261293-978-0470261293-15238/

Microsoft Visual C# 2017 An Introduction to Object Oriented


Programming 7th Edition by Joyce Farrell ISBN 1337102100 9781337102100

https://ebookball.com/product/microsoft-visual-c-2017-an-
introduction-to-object-oriented-programming-7th-edition-by-joyce-
farrell-isbn-1337102100-9781337102100-25038/

C Programming An Object Oriented Approach 1st Edition by Behrouz


Forouzan, Richard Gilberg 0073523380 9780073523385

https://ebookball.com/product/c-programming-an-object-oriented-
approach-1st-edition-by-behrouz-forouzan-richard-
gilberg-0073523380-9780073523385-15328/
Object Oriented Programming C Simplified 1st Edition by Hari Mohan
Pandey 978-9381159507

https://ebookball.com/product/object-oriented-programming-c-
simplified-1st-edition-by-hari-mohan-pandey-978-9381159507-15298/

An Introduction to Object Oriented Programming With Java 5th Edition


by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-17244/

An Introduction to Object Oriented Programming With Java 5th Edition


by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15256/

An Introduction to Object Oriented Programming With Java 5th Edition


by Thomas Wu 0073523305 9780073523309

https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15330/

Computer Science An Object Oriented Approach Using C 1st edition by


Behrouz Forouzan, Richard Gilberg 9780077418755 0077418751

https://ebookball.com/product/computer-science-an-object-
oriented-approach-using-c-1st-edition-by-behrouz-forouzan-
richard-gilberg-9780077418755-0077418751-15228/
Macmillan Computer Science Series

A Abdellatif, J. Le Bihan, M. Limame, Oracle - A User's Guide


I. O. Angell, High-resolution Computer Graphics Using C
I. O. Angell and G. Griffith, High-resolution Computer Graphics Using Pascal
C. Bamford and P. Curran, Data Structures, Files and Databases, second edition
P. Beynon-Davies, Database Systems
P. Beynon-Davies, Information Systems Development, second edition
Linda E.M. Brackenbury, Design of VLSI Systems - A Practical Introduction
Alan Bradley, Peripherals for Computer Systems
P.C. Capon and PJ. Jinks, Compiler Engineering Using Pascal
B. S. Chalk, Computer Organisation and Architecture
Eric Davalo and Patrick Nalill, Neural Networks
Joyce Duncan, Lesley Rackley and Alexandria Walker, SSADM in Practice
D. England et al., A Sun User's Guide, second edition
Jean Ettinger, Programming in C++
lS. Florentin, Microprogrammed Systems Design
Michel Gauthier, Ada - A Professional Course
M.G. Hartley, M. Healey and P.G. Depledge, Mini and Microcomputer Systems
MJ. King and lP. Pardoe, Program Design Using JSP - A Practical Introduction,
second edition
Bernard Leguy, Ada - A Programmer's Introduction
M. Leonard, Database Design Theory
David Lightfoot, Formal Specification Using Z
AM. Lister and R.D. Eager, Fundamentals of Operating Systems,fifth edition
Tom Manns and Michael Coleman, Software Quality Assurance, second edition
G.P. McKeown and VJ. Rayward-Smith, Mathematical Foundations for Computing
B.AE. Meekings, T.P. Kudrycki and M.D. Soren, A book.on C, third edition
RJ. Mitchell, C++ Object-oriented Programming
R.J. Mitchell, Microcomputer Systems Using the STE Bus
RJ. Mitchell, Modula-2 Applied
J.P. Pardoe and M.l King, Object Oriented Programming Using C++
- An Introduction
Pham Thu Quang and C. Chartier-Kastler, MERISE in Practice
Ian Pratt, Artificial Intelligence
F.D. Rolland, Programming with VDM
S. Skidmore, Introducing Systems Analysis, second edition
S. Skidmore, Introducting Systems Analysis, second edition
AG. Sutcliffe, Human-Computer Interface Design, second edition
C.l Theaker and G.R. Brookes, Concepts of Operating Systems
M. Thorin, Real-time Transaction Processing
DJ. Tudor and U. Tudor, Systems Analysis and Design - A Compan'son ofStructured
Methods
Al Tyrell, Eiffel Object-Oriented Progru,nming
Other titles
Ian O. Angell and Dimitrios Tsoubelis, Advanced Graphics on VGA and XGA Cards
Using Borland C++
N. Frude, A Guide to SPSSIPC+, second edition
Peter Grossman, Discrete Mathematicsfor Computing
H. Harper and A. Meadows, GNVQ Advanced Information Technology
Percy Mett, Introduction to Computing
P.D. Picton, Neural Networks
Tony Royce, COBOL - An Introduction
Tony Royce, Structured COBOL - An Introduction
Tony Royce, C Programming
Object Oriented Programming
Using C+ +
An Introduction

John Pardoe and Melv King


© J.P. Pardoe and M.J. King 1997

All rights reserved. No reproduction, copy or transmission of


this publication may be made without written permission.

No paragraph of this publication may be reproduced, copied or


transmitted save with written permission or in accordance with
the provision of the Copyright, Designs and Patents Act 1988,
or under the terms of any licence permitting limited copying
issued by the Copyright Licensing Agency, 90 Tottenham Court
Road, London WIP 9HE.

Any person who does any unauthorised act in relation to this


pUblication may be liable to criminal prosecution and civil
claims for damages.

The authors have asserted their rights to be identified as


the authors of this work in accordance with the
Copyright, Designs and Patents Act 1988.

First published 1997 by


MACMILLAN PRESS LTD
Houndmills, Basingstoke, Hampshire RG21 6XS
and London
Companies and representatives
throughout the world

ISBN 978-0-333-69241-7 ISBN 978-1-349-14449-5 (eBook)


DOI 10.1007/978-1-349-14449-5

A catalogue record for this book is available


from the British Library.

This book is printed on paper suitable


for recycling and made from fully
managed and sustained forest sources.

10987654321
06 05 04 03 02 01 00 99 98 97
Contents

Preface ix

1 Programming Concepts 1
1.1 Computer programs 1
1.2 The way a program uses the computer's memory 2
1.3 Input and output of data 4
1.4 Computer program development 6
1.5 The user requirements specification 6
1.6 The design stages 7
1.7 Detailed design using pseudo-code 7
1.8 The programming stage 8
1.9 Compiling, running and testing a program 8
1. 10 Documenting and maintaining pro grams 9
1.11 Writing high-quality computer programs 10
1.12 Exercises 10

2 Object Oriented Programming Concepts 12


2.1 Concept of a model 12
2.2 Object classes and objects 13
2.3 Inheritance 15
2.4 Encapsulation 17
2.5 Polymorphism 17
2.6 Modelling a system using object classes 17
2.7 Exercises 18

3 A First Program 21
3.1 The model for our first program 21
3.2 The C++ code for our first program 22
3.3 Coding style 26
3.4 Pseudo-code for a sequence 27
3.5 Exercises 28

v
vi Contents

4 An Introduction to Inheritance 29
4.1 Using a header file 29
4.2 Inheriting code from our first program into a second
program 31
4.3 Exercises 34

5 Arithmetic 36
5.1 Integers 36
5.2 Assignment statements and integer arithmetic 37
5.3 Real arithmetic 38
5.4 A model for a student's assessment in a subject 38
5.5 Using integer and real numbers, the ini tialise
function 42
5.6 The display functions 44
5.7 Exercises 46

6 An Introduction to Selection 49
6.1 Further development of a model for a student's
assessment in a subject 49
6.2 The i f statement 49
6.3 The if-else statement 52
6.4 Relational operators 53
6.5 Nested selections 54
6.6 Compound statements 56
6.7 Exercises 57

7 Further Concepts for Selection 62


7.1 Further development of a model for a student's
assessment in a subject 62
7.2 Logical operators 62
7.3 Assigning and comparing characters 66
7.4 The swi tch statement 67
7.5 Exercises 71
Contents vii

8 Repetition 74
8.1 Refining the input processes for the student's marks 74
8.2 The whi le statement 77
8.3 The for statement 80
8.4 The do-while statement 82
8.5 Exercises 85

9 Functions 88
9.1 The function call 88
9.2 The function definition 89
9.3 A revised version of the student marks object class 90
9.4 Call by value parameters 91
9.5 Function results 93
9.6 Call by reference parameters 96
9.7 When to use call by value and call by reference 101
9.8 Exercises 101

10 Constructors and Destructors 106


10. 1 Constructors 106
10.2 Constructors with parameters 109
10.3 Destructors 111
10.4 Exercises 112

11 Introduction to Arrays 114


11.1 The need for arrays 114
11.2 Using an array 114
11.3 Exercises 121

12 Arrays of Objects 124


12.1 Using an array of objects 124
12.2 Aggregation 128
12.3 Exercises 129

13 Two-dimensional Arrays 132


13.1 Using a two-dimensional array 132
13.2 An alternative approach for entering the data 138
13.3 Exercises 140
viii Contents

14 Object Lifetime and Dynamic Objects 143


14.1 Object lifetime 143
14.2 The scope of variables 144
14.3 The scope of objects 145
14.4 Dynamic variables 147
14.5 Dynamic objects 149
14.6 Exercises 155

15 Streams and Files 161


15.1 Disk files 161
15.2 Streams 162
15.3 File streams 164
15.4 Object persistence 172
15.5 Exercises 173

16 Introduction to Polymorphism 177


16.1 What is polymorphism? 177
16.2 Operator overloading 177
16.3 Operator functions 179
16.4 Function overloading 181
16.5 Generic functions 184
16.6 Exercises 187

Appendix A: Object Classes Used in Examples 189

Appendix B : Solutions to Exercises 193

Appendix C : C++ Keywords and Operators 246

Appendix D : The ASCn Character Set 248

Index 249
Preface

Aim of the book


The increasing use of object oriented techniques for software development is now
a fact of life.
• Increasingly large software projects must use object oriented techniques.
• It has been predicted that object oriented programming will provide the
focus for all new software development.
• The concepts of software reuse are becoming increasingly important.
The aim of this book is to provide an introductory course in the use of object
oriented computer programming using the C++ language. It has been especially
designed to teach those with no previous experience of computer programming.
Many student programmers learn more traditional, procedural approaches to
computer programming before tackling the quite different concepts found in
object oriented programming; many students find this switch difficult. Hence the
need for an introductory text that encourages students to understand basic
programming concepts and techniques within an object oriented framework.
Other books in this area have tended to incorporate so much material, much
of it difficult to assimilate, that the novice reader could well be discouraged. The
temptation to include too much has therefore been resisted. Complex terminology
has been eliminated or explained in simple terms.
What we have included are the basic concepts and terminology of object
oriented programming that will enable the reader to 'get started' and build up the
confidence to move on to more advanced texts.

Content of the book


The book develops the techniques of object oriented programming at the same
time as gradually introducing the language features of C++. Procedural aspects
that should be included in any introductory text, such as the use of structured
programming techniques, have been incorporated.
Many straightforward examples are used to introduce and illustrate both new
techniques and language features.

ix
x Preface

Chapter I covers basic concepts in order that the reader can appreciate what
a computer program is. The development of a program is then put in context by
describing briefly, in general terms, the various stages involved. Chapter 2
introduces the basic object oriented terminology and illustrates how object classes
are used to model a very simple system.
Having introduced a C++ program in chapter 3, the important concept of
inheritance and the use of a header file are covered in chapter 4.
Chapters 5 to 8 cover, within an object oriented context, facilities found in
most procedural languages, such as basic data types, arithmetic and control
constructs for selection and repetition. The need for, and the difference between,
the constructs for both selection and repetition are emphasised.
Chapter 9 concentrates on the use of programmer-defined functions; con-
cepts are introduced by referring to functions already used including those found
in standard C++ libraries. The next chapter on the use of constructors and
destructors is a natural development.
The need for arrays and their use is described in chapters 11 to 13. The
concept of an array of objects enables the difference between inheritance and
aggregation to be explained.
Scope rules and object lifetime are emphasised in chapter 14 before introduc-
ing the concept of pointers for dynamic variables and objects. Then chapter 15
covers the use of file streams in general and how they may be used to facilitate
object persistence.
Finally, in chapter 16, we introduce some of the fundamental concepts of
polymorphism and use appropriate C++ language constructs in straightforward
illustrative examples.

Use of the book


Each chapter starts with the learning objectives for the chapter and concludes with
a number of exercises. The chapters have been kept relatively short so that the
reader can use the exercises to ensure that concepts are understood and techniques
mastered in accordance with the objectives.
There are two types of exercise. The first type is a self-assessment question
designed to reinforce major points by referring the reader back to specific
examples in the chapter. The second type of exercise involves either amending
one or more of the example programs or writing a new program. The reader is
strongly advised to attempt all the exercises and for the second type to run the
program and get it working. Sample solutions to all the exercises are given in
appendix B.
An outline design, indicating how each function achieves a specific task, is
provided in most of the examples and all the practical exercises; it is written in a
form of structured English (pseudo-code). This emphasises to the reader the
importance of understanding 'how to solve the problem' before 'coding in C++'.
It also demonstrates how to write pseudo-code and provides appropriate help for
the novice when attempting the practical exercises.
Preface xi

A model and corresponding object class for a student's performance


(examination and practical mark) in a subject (module) is introduced in a
simplified form in chapter 5. This model is developed and refined in subsequent
chapters as additional features of object oriented programming are introduced.
This case study approach promotes the learning process as well as providing an
awareness of the reality of software systems development using object oriented
programming. A diagram showing all the object classes that are eventually used
and the relationship between them is given in appendix A. This diagram also
indicates where each class is first introduced in the text enabling the reader to
refer back, if necessary, for the full specification.

Acknowledgement
The authors are grateful to Neil Hepworth of South Bank University for his
helpful and constructive comments made while reviewing this book.
1 Programming Concepts

Objectives for this chapter


Familiarity with the programming terms:
• identifier, data type
• integer, float, character and string
• constants and variables
• source code and coding
• compiler, compilation, syntax errors
• program execution, run-time errors, logical errors
• testing, test data, bugs, debugging
• user requirements specification, program design, documentation and
maintenance
• sequence, iteration and selection constructs
• program characteristics: correctness, reliability, modifiability and clarity.
Understanding of:
• how the computer and the programmer identify data items
• how values may be given to data items
• how data are accepted and displayed.

1.1 Computer programs


A computer program is a sequence of instructions, often a very long sequence,
that can be held in a computer's internal storage area (memory) and executed at
speed. The instructions are normally first written down in a human-readable
form, called the source code or program code, and entered into the computer's
memory or a computer file via the keyboard. The source code is written using a
high-level programming language, ~uch as Pascal, C, C++, Ada, COBOL.
Instructions, written in these languages are referred to as program statements.
This source code has to be translated into a form that can be understood by the
electronics of the computer; this is known as the machine code and the
translation process is called compilation.
A computer program will normally take some data values, store the data
in memory and then manipulate the values to produce the required results. For
example, a simple program might take in ten temperature readings in degrees

1
2 Object Oriented Programming Using C++

Fahrenheit and convert them to degrees Celsius. A more complex program for a
company's payroll system would take in a great deal of data, staff names, tax
codes, salary grades and so on, in order to produce results in the form of
payshps and cheques or bank credits. The values that the program takes in are
known generally as the input data and the results are often referred to as the
output. This can be visualised as in figure 1.1.

..
Program

....
held in memory
Data values manipulates data r- Results
stored in memory

Figure 1.1

1.2 The way a program uses the computer's memory


Within the computer itself, each unit of memory (called a byte) is accessed or
addressed by a unique reference number. In some cases a single byte is
addressed, in others two or more bytes are addressed as if they are one complete
unit of memory.
To make programs more readable, however, the programmer refers to
parts of the computer's memory by an identifying name, called an identifier.
Since different types of data are stored differently, we also need the concept of a
data type. The standard data types used in most computer programming
languages are: integer, float (or real), character, and string. An integer item
is restricted so that it will contain only whole numbers within a pre-specified
range, for example in the range -32,768 to +32,767. Data of type float is for
real numbers, that is numbers that may contain a decimal part. While integer
and float data items use more than one byte, an item of type character uses only
one byte and is restricted to contain just one character. The character may be
any that is recognised by the computer, including some special ones as well as
the usual letters of the alphabet and numbers. Finally, a text string is a number
of characters such as a person's name or the name of a product, stored in a
succession of bytes.
We can illustrate the way in which the programmer and the computer
access items of data by considering the diagram in figure 1.2.
If we imagine that the diagram represents a portion of the computer's
memory and that each cell is one byte, we can give a unique numerical
reference to each byte by using the column and row numbers. Hence the cell at
the top left-hand comer containing the letter B is referred to as byte 00, the one
Programming Concepts 3

to its right as byte 01 and the one directly beneath it as byte 10, and so on.

9 I I
Figure 1.2

Within a program, all we have to do is specify (or declare) the names of


the identifiers (in this case, a_letter, a_number, a_real_number and
a_char_string) and state which data type they are to contain (character,
integer, float, string), the computer references and in most cases the number of
bytes to be used are calculated during the compilation process.
Areas of computer memory reserved to hold data in a computer program
may have initial values (or constant values) pre-loaded into them automatically
when the program is first run, or values may be assigned to the areas during the
running of the program. This is illustrated in figure 1.3.

computer memory
constant value !!

computer memory
program statement
a_letter = 'B' ;

computer memory
Identifier a_letter

Figure 1.3
In this diagram, we have three areas of computer memory. At the top we
have a single byte that is of data type character and it contains the constant
4 Object Oriented Programming Using C++

value B that it will retain for the duration of the program. Not surprisingly, we
call this kind of data constant data. At the bottom of the diagram, we have also
a single byte that has been given the identifying name a_letter and the data
type character. Because a_letter may be given any value during the running
ofa computer program it is referred to as a variable identifier (or just variable
for short). The third area of memory shown is that which is needed to hold a
computer instruction written in the C++ language to change the value of the
identifier so that it contains the letter B; we call this kind of instruction an
assignment statement, it is one way of changing the values held in a computer
program's memory. Another way is depicted in figure 1.4.

computer memory
constant value 12

~
computer memory
Identifier a number 1 32121
before after

Figure 1.4

Here the computer instruction shown, again in the C++ language, is one
that adds a fixed value (the constant number 12) to the existing contents of the
variable identifier a_number giving it a new value. Again, three areas of
memory are shown; the two data areas would be integers.
The above examples use elementary data types containing a single item of
data. Groups of data items may also be declared using a single identifier. The
components of these groups may all be of the same type or of a number of
different types.

1.3 Input and output of data


As mentioned in section 1 .1, a program will normally take in some input values
and produce results known as output.
The input values can be held in computer files on disk or typed at the
keyboard. In either case, the data are first stored in a small area of memory
called a buffer. When a computer program issues an instruction to read or
accept the data, the required value(s) are transferred into memory areas within
Programming Concepts 5

computer memory
program sraremenr
cin.get (name_oCwrlter, 6) ;

computer memory
Identifier name of writer L........L_.L..~_....L........I

Figure 1.5

mouse
monitor screen

screen buffer

computer memory
program statement
caut« animal« endl ;

Icomputer
L..-L_.L........L_...L.........I
memory
Identifier animal

Figure 1.6

the program. This general process for keyboard input is shown in figure l.5.
The program statement illustrated here is written in the C++ language.
Note that the programmer generally does not need to be concerned with
6 Object Oriented Programming Using C++

the buffer.
The process of producing output is almost the reverse of obtaining input
data. Writing data to a disk file and displaying data on the monitor screen also
involves a memory buffer that we do not need to concern ourselves with unduly.
For such output activities, we need to do two things: identify the memory area
from which the data will be taken and indicate where the output is to be placed;
the name of the computer file and in some cases the position in the file or the
position on the screen where the data are to be displayed. The general process
for displaying just one item on the screen is depicted in figure 1.6. Again, the
program statement is written in the C++ language.

1.4 Computer program development


The stages of computer program development are most often referred to as the
software life-cycle. A number of different models have been produced to
describe this life-cycle with the major differences being the breakdown of the
different stages and the way certain stages may be repeated or occur
concurrently.
In the following sections we describe the stages separately, but it should be
understood that the stages may overlap and that it may be necessary to return to
a previous stage. For example, the testing stage if not completed to the
developer's satisfaction could require adjustments at the programming stage.
A life-cycle model can be applied to a single computer program or a
collection of programs that make up a complete computer system.

1.5 The user requirements specification


The user requirements specification is normally a document that describes in
precise terms what is required of a computer program (or computer system). It
is produced after an analysis process in which systems analysts consult with the
probable eventual users of the system to explore the current and future
requirements in a specific business or technical area. It will be concerned with
what will actually be delivered to the users at the end of the development
process or each development stage.
The user requirements specification is the result of a refining process
whereby general statements of desire or intent to produce a computer system are
formalised; it becomes the foundation for the system's development. An
analysis process (called object oriented analysis or OOA) will define the
components (objects) of the real world that are to be modelled in the proposed
computer system. This will focus on the information that is required to be
processed as well as the functional requirements (specific activities).
The details of how the information needs of the system are to be met or
how the specific requirements are to be provided are not produced at this stage.
Programming Concepts 7

1.6 The design stages


The design stages translate the user requirements into a representation of the
proposed system that can be assessed for quality and can facilitate the
production of computer program code.
The systems design stage is concerned with all aspects of the system, not
just the production of computer programs. For example, the design of clerical
procedures and management of the system would need detailed consideration as
well as what the computer software is to achieve.
The software design stage is concerned with how the real-world objects
identified in the analysis stage are to be represented in the computer system and
how they may interact.
This will include how and where data are to be stored within computer
files or in computer memory during the running of computer programs. It will
involve the determination of what data are to be grouped together and what
types of data storage are needed for storing different kinds of values.
It will also include a definition of the relationship between the major
components of the system (or program) and design representations of the
detailed processes that the system requires.

1. 7 Detailed design using pseudo-code


As we shall see in the next chapter, a large program is normally broken down
into self-contained parts called functions. Each function consists of the steps
required to achieve a specific task; eventually it will be written in program
statements using the appropriate programming language. First, at this stage, the
tasks are written in an informal notation called pseudo-code.
Pseudo-code contains normal language statements to describe the actions
required and also more formalised control statements to indicate the logic. For
example, the normal language statements for the c++ statements shown in
figures 1.3 to 1.6 are:
Assign 'B' to a_letter
Add 12 to a number
Accept name of writer (from keyboard)
Display animal (on monitor screen)
Control statements are similar to C++ statements and will be described in
detail in the appropriate chapters.
We can describe the logic of most functions using the three constructs:
sequences, iterations and selections.
A sequence is a number of statements that will be executed in the order
written from top to bottom of the paper.
An iteration is the repetition of one or more statements.
A selection is a choice between two or more different actions depending
on the value of a data item or some other condition.
8 Object Oriented Programming Using C++

1.8 The programming stage


Writing computer programs involves far more than just learning a program-
ming language; it is very easy to write poor programs. Problems that we are
trying to solve by computer must be carefully defined. Then when the definition
or specification is clearly understood, we can design a solution to the problem
using pseudo-code. Only after the design process is complete should we
elaborate the design by producing programming language statements (or
program code) from it. This is known as the coding process or implementing
the design.

1.9 Compiling, running and testing a program


As mentioned in section 1. 1, a source program cannot be understood directly by
the computer; it must first be translated into an equivalent program in the
machine language (code) of the computer.
This process of translation (compilation), is performed by a program
stored within the computer called a compiler. This produces a machine-
readable form of the program that is combined with code from the compiler
libraries using a process called linking. This two-stage process produces a
machine language program that is then stored either in a disk file or in
computer memory, but it will only do this if there are no mistakes in the way
you have used the language. If there are syntax errors, that is, mistakes in the
program language grammar, then the compiler will produce error messages.
Once we have produced a program without syntax errors and have a
machine language program in computer storage, we can go to the next stage,
execution. The computer executes the machine code instructions and may
produce the results you require. However, at this stage further errors can occur.
Run-time (or execution) errors occur when the programmer has made a
mistake that was not a syntax error, but still contravenes the computer's rules
(for example, trying to divide a number by zero). In such cases an appropriate
run-time error message is produced.
Logical errors occur even when there are no syntax or run-time errors.
The symptoms for these errors are results that are not as expected. The design
may be wrong or they may arise because the programming language statements
are misused or in the wrong order.
The error messages will help us to find the syntax and run-time errors.
Detecting logical errors can obviously be more difficult. It is vitally important
that we test our program, possibly with a range of data values, known as test
data, to ensure that it works according to its specification. The task of finding
out why a program is not working to specification is called debugging. This is
because logical errors in programs are called bugs. If we discover that the
program is not correct for any reason, then we must change the contents of the
source program.
Programming Concepts 9

1.10 Documenting and maintaining programs


Documentation is that information concerning a program that is needed by both
users of the program and those with responsibility for maintaining the program.
The former need sufficient detail to enable them to use the program properly.
The latter need sufficient detail to enable them to modify, improve and correct
the program.
Good user documentation is essential if a program is to be a useful tool;
an outstanding piece of software is useless if no one knows how to use it. The
contents and style of a user guide will obviously vary depending on the target
audience. For example, a user guide for a software tool that is to be used by
experienced programmers will need almost no information about how to switch
the computer system on. However, a user guide for the general public, such as a
Windows 95 User Guide will need to contain instructions on how to tum on the
computer and how to use disks.
Good technical documentation is essential for maintaining a program.
We may have to correct errors or we may decide to add features and improve
the program. Programs have actually been thrown away because they are too
difficult to change. A technical manual should enable someone other than the
author, but who is familiar with the design methods and documentation
standards, to understand fully the program's purpose and the way that the
purpose has been achieved.
When do we write this documentation? The rule is, document as you go
along. Much of the user documentation should be written as we start to design a
program, it can serve as a set of specifications. As we proceed with the
development of a program, much of the technical documentation can be written.
This should ensure that the documentation will be of a high quality. If
documentation is left until the end of the project, important details are often
omitted.
When the program is complete and full-scale testing has been done, the
documentation should be reviewed to check that it meets its stated purpose and
that it is accurate and consistent with the finished program.
Maintenance can be defined as "anything that happens to program code
after the initial implementation". It can be classified into four areas: corrective
maintenance, adaptive maintenance, perfective maintenance and preventive
maintenance.
The most obvious form of maintenance is error fixing or corrective
maintenance. Here we concern ourselves with removing a known fault from a
program or system.
Adaptive maintenance is the act of modifying a software unit so that it
interfaces with a changing environment. It commonly occurs when changes in
hardware, the operating system or other system software force alterations to be
made to application programs.
Perlective maintenance is the most common type of maintenance
encompassing enhancements both to the function and the efficiency of the code.
10 Object Oriented Programming Using C++

It usually arises from requests for change to the user requirements specification.
Preventive maintenance is the process of changing software to improve
its future maintainability or to provide a better basis for future enhancements.

1.11 Writing high-quality computer programs


Writing computer programs is both exciting and creative. It also needs discip-
line and a systematic approach if the desired results are to be achieved. This is
because there may be many ways of writing a computer program but not all of
them will lead to the production of a program of the required quality.
To produce high-quality programs, we need to be aware of the four basic
criteria for quality. They are: correctness, reliability, modifiability and clarity.
Correctness is obviously an essential quality in that we would always wish
to ensure that a computer program does what it is supposed to do in the most
appropriate manner. It must satisfy its requirements or specification in all
aspects.
A computer program must also be reliable in that it will always produce
predictable results every time it is run. Most computer programs will operate on
different sets of data each time they are run hence there may be many different
results to be produced.
Of increasing importance as a requirement of high-quality software is
modifiability. Most computer programs will require some modification, or
maintenance, at some time because the requirements of the program may
change or better techniques are discovered or even to correct residual errors.
To be modifiable a computer program must be easy to understand. Hence
clarity is an essential characteristic of high-quality programs. It is easy to
produce over-complex programs. However, it should be noted that bad pro-
grammers produce unnecessarily complicated programs; good programmers
only ever produce simple, clearly understood programs.
Our goal should be to provide high-quality programs using a method of
proceeding from a statement of the program's requirements to high-quality
solution in a reasonable manner. Object oriented design and programming is a
means of achieving this.

1.12 Exercises
1.12.1 State in your own words what is meant by the following terms:
(a) Compilation of a computer program.
(b) Identifier.
(c) Data type.
(d) Variable.
(e) Keyboard buffer.
Programming Concepts 11

1.12.2 Answer the following questions:


(a) How does a computer programmer identify a particular part of the
memory in a computer program?
(b) What different kinds of data might you wish to use in a computer
program?
(c) What is an assignment statement?
1.12.3 State in your own words what is meant by the following terms:
(a) The user requirements specification.
(b) Pseudo-code.
(c) Testing.
(d) The reliability of a computer program.
1.12.4 Answer the following questions:
(a) Why is the software life-cycle not a strictly sequential set of
development stages?
(b) What type of errors may be discovered when compiling and then
testing a computer program?
(c) What is the process offault diagnosis more commonly called?
(d) What is the difference between user-documentation and technical
documentation?
(e) What are the four types of program or system maintenance?
(f) Why are simplicity and clarity necessary requisites of a good
computer program?
2 Object Oriented Programming Concepts

Objectives for this chapter


Familiarity with the object oriented tenns:
• object and object class
• object class data, object class behaviour and functions
• an instance of an object class
• inheritance, base class, derived class
• encapsulation
• private and public parts of an object class
• polymorphism.
Ability to:
• draw a diagram to represent a simple object class
• draw a diagram to illustrate inheritance of an object class
• model a simple object class in tenns of its data items and behaviour
(functions).

2.1 Concept of a model


Computer programs model or simulate real-world or imaginary-world objects
and their interactions. We can illustrate this by considering a simple computer
game in which the user guides a little figure around a maze. The little figure is
a model of a person who can walk around a maze. As with all models, because
they are models, they do not have all of the facilities of their real-world
counterparts. Our little figure may only be required to "walk" in each of the
four compass directions (because the walls of the maze are at right angles to
each other), and "recognise" when it reaches a wall, and "decide" which
direction to take next. Note that the verbs "walk", "recognise" and "decide"
describe the behaviour or the functions of the model. Other aspects of the
model might be its colour and the size of the figure. These attributes are
infonnation (or data) that describe the structure and nature of the model. They
do not necessarily influence the behaviour of the model, but may do so, for
example, if an aspect of the behaviour was a function to change the colour or
size.
We can describe a real-world object in tenns of its component parts (its

12
Object Oriented Programming Concepts 13

data) and what it does (its behaviour). When we produce a model of such an
object, we decide which features we are going to use in the model. First we look
at the component parts and choose what we need in our model; we may ask
ourselves "Which of the component parts of the object are important in our
simulation?" Next, we choose those functions of the behaviour of the object that
we wish to simulate.
In what sense do we produce a model or use simulation when developing a
computer program? Clearly, it is not in the same sense as building a model of a
person from clay or wood. Rather, we use pictures, words and numbers. We
manipulate these in the computer to give some desired affect possibly on the
monitor screen. For example, a model of a person in a computer would probably
consist of graphical representations of a person in different poses as well as
descriptive data in words concerning such things as the person's name and
numerical data for such things as size.
So, the model's data can be described in terms of graphics, words and
numbers, but what of the model's behaviour? Each aspect of the behaviour
represents a function to be defined. For example, our little figure in the maze
has a "walk" function. This would be quite a complicated function to imple-
ment; others in different simulations could be more straightforward. For
instance, if we were to produce a computer function to simulate the withdrawal
of money from a bank account, it might be just two simple calculations: subtract
sum of money from account; and add sum of money to contents of wallet.
Object oriented programming emphasises the interconnections between
data items and functional behaviour in a way that puts together information and
processing rather than processing alone. An object is a component imple-
mented in software such that it contains a definition of its data and the
functions (operations) that describe the object's behaviour or how the data is
used or interacts with its environment.

2.2 Object classes and objects


It would be very wasteful to describe uniquely each individual object as we need
them because most objects tend to have some things (data or behaviour) in
common with others. Often it is convenient to group objects together such as in
the field of zoology in grouping animal species with common characteristics.
Such groupings in programming are called object classes.
Object classes can be thought of as descriptions of categories or groups of
objects. For example, the object class car may have a description pertaining to
the relevant features that· apply to all cars. All cars have wheels and an engine;
they consume fuel and so on. The object class employee might have the
general description of all people employed in a certain situation; and would
likely comprise name, date of birth and current salary among other areas of
interest.
We can apply what we have already seen when introducing the notion of
14 Object Oriented Programming Using C++

models to object classes. What we know about the component parts of an object
class is called the member data (or attributes). The member data for an
employee could be name, date of birth and so on. The things we can do
with an object class or its data are called its behaviour. For example, we can
give an employee a pay rise or amend an employee's qualifications. The
definition of the member functions that define an object's behaviour is part of
an object class's description. Each function will normally consist of the actions
required to achieve a specific task.
One way of describing the object class for an employee is by means of an
object schema as given in figure 2.1.

Class: employee t--Identification

name
date of birth
qualifications r---Data
telephone number
etc ..

Amend qualifications
Get telephone number
Calculate age -Functions
Display details
etc ..

Figure 2.1

Notice how we identify the object data and the object behaviour
(functions). In a full description, we would normally have one or more
functions for each item of data. If we asked "What can we do with each item of
data?", the answer would generate a list of functions. For example, if we asked
this question of just one data item, say telephone number, we would likely
generate: insert new number, amend existing number, delete
number, display full number, extract dialling code, and
perhaps many more.
An object is said to be an instance of an object class. This means that an
object is an implementation of an object class definition. We can liken an object
to a more complex version of a variable in a program; a variable has a type that
describes its characteristics (for example, an integer is a whole number within a
certain range); an object has an object class that describes its characteristics.
For example, we might have objects Jim_Brown and Dave_Thomas of the
Object Oriented Programming Concepts 15

object class employee.


Objects have all the data items and functions of their class. Hence, to
change Jim_Brown' s qualifications, we would use the function amend
qualifications. The object oriented terminology for this is that we "send a
message to the object"; so we send the message amend_qualifications
to Jim Brown.

2.3 Inheritance
If we develop the example of the object class employee, it is easy to see that
there are different kinds of employee all having a common set of characteristics
as described in the definition of the object class employee. Also we can see
that different kinds of employee would have additional, more specific,
characteristics depending on their position or type of work. For example, an
employee who is a manager might be responsible for a number of staff and may
have a secretary (who can be described by name or perhaps employee number).
We therefore need to use the attributes and behaviour from the original class
and extend them to include the particular characteristics of each type of
employee.
The concept of inheritance allows us to produce another class such that it
has all the data and functions of the class upon which it is based (called the
base class). The new class called a derived class can be thought of as a
specialised version of the more general base class.
So, a class that inherits the data and behaviour of another is called a
derived class often referred to as a descendant or a child class. The class that
provides the inherited characteristics is called the base class also referred to as
an ancestor or parent class.
The way in which a derived class is formed by inheritance from a base
class is depicted in the object schema shown in figure 2.2.
An entire inheritance (or classification) hierarchy (like a family tree) may
be constructed from a single class with a number of descendants. This is
illustrated in figure 2.3 where the base class employee has three descendants:
manager, secretary and technician. The manager derived class is
also a base class with one descendant: sales manager.
Note that the inheritance of data and behaviour in a program is usually
achieved by sharing the code and not duplicating it, so the inherited functions
and data do not actually exist in the derived class. To illustrate this, imagine we
wish to use the function get telephone number from the manager
class, the computer would first look for the function in manager, then on
failing to find it there it would look further up the class hierarchy until the
function is found.
16 Object Oriented Programming Using C++

Class: employee Derived class: manager

name
date of birth
qualifications
telephone number
etc ..

Amend qualifications
Get telephone number
Calculate age
Display details
etc ..
~

Decrease number of staff


Change secretary
etc ..

Figure 2.2

employee
(base class)
I
I I I
manager secretary technician
(base class &
derived class) (derived class) (derived class)

I
sales
manager
(derived class)

Figure 2.3
Object Oriented Programming Concepts 17

2.4 Encapsulation
Putting data and functions together is called encapsulation. A basic principle
of object oriented programming is that member data should only be accessed via
the object's own functions. To achieve this, in all but exceptional cases,
member data items are described as private or protected. Functions may also
be private. If data or functions are to be accessed directly from outside the
object class, they are defined as public.
Encapsulation separates how an object class behaves from how it is
implemented and therefore allows the details of an object class to be modified
without requiring changes to applications that use the object class. The object
class can be treated as a black box, the programmer needs only to know what
functions can be requested and not how they are carried out.

2.5 Polymorphism
Polymorphism means having many forms. In object oriented programming it
refers to the way in which different objects may respond to the same message in
different ways depending on the type of the object. For example, manager and
technician objects should respond differently to the Display details
message. The functions need to be different even though the purpose of the
function is the same, that is, to display the details of the object concerned.
There are a number of ways to implement polymorphism, we will discuss
these later in the text.

2.6 Modelling a system using object classes


Suppose we wish to model the activities of a University; we could define an
object class person with derived classes student and tutor and an object
class course. To keep things simple, let us assume that these are the only
objects of interest and their data items are as follows.

person: name,
reference number,
year of joining the University.
student: as for person,
year of the course.
tutor: as for person,
years of teaching experience.
course: name,
number of students.
Again, to keep it simple, their functions are:
18 Object Oriented Programming Using C++

person: Ini tial.ise detail.s: to allow the entry of the


three data items for a person.
Display details: to display the values of all
three data items of a person.
student: Ini tialise details: to allow the entry of the
three data items for a person, plus the year of the
course.
Displ.ay detail.s: to display the values of all
three data items of a person, plus the year of the
course.
tutor: Ini tial.ise details: to allow the entry of the
three data items for a person, plus the years of
teaching experience.
Display detail.s: to display the values of all
three data items of a person, plus the years of
teaching experience.
course: Ini tial.ise details: to allow the entry of
course name and setting the number of students to
zero.
Add new s tuden t: to use the student initialise
details function and add one to the number of
students.
Display details: to display the course name
followed by the number of students on the course.
We can represent the relationship between the object classes using an
object schema similar to that shown in figure 2.2, as follows in figure 2.4. Note
that, in this case, for the derived classes the functions are over-ridden
(redefined) because they must be different for each class.

2.7 Exercises
2.7.1 State in your own words what is meant by the following object oriented
terms:
(a) An object class.
(b) A function.
(c) An attribute.
(d) Inheritance.
(e) Encapsulation.
2.7.2 Answer the following questions:
(a) In what way is an object similar to a variable?
(b) What are two other names given to derived classes?
(c) What is a software "black box"?
Object Oriented Programming Concepts 19

Class: person

name
reference no.
Derived class: studen Derived class: tutor
year of joining

Initialise
Display details

year of the course years of experience

Initialise Initialise
Display details Display details
Class : course

name
number of students

Initialise
Display details
Add new student

Figure 2.4

2.7.3 Please examine the object schema in figure 2.2 and answer the
following questions.
(a) What data members are inherited by the derived class manager
from employee?
(b) What other data members might the derived class manager have?
(c) What other derived classes do you think might be derived from the
class employee?
2.7.4 In a warehouse system, the following objects have been identified as
having the data items:
container: name,
location,
weight.
carton: as for container,
destination,
number of components.
20 Object Oriented Programming Using C++

case: as for container,


quality control reference.

The functions are:


container: Initialise details: to allow the entry of
the three data items for a container.
Display details: to display the values of all
three data items of a container.
carton: Ini tialise details: to allow the entry of
the three data items for a container, plus the
destination and number of components.
Display details: to display the values of all
three data items of a container, plus the
destination and number of components.
Amend the number of components.
Amend the destination.
case: Ini tialise details: to allow the entry of
the three data items for a container, plus the
quality control reference.
Display details: to display the values of
all three data items of a container, plus the quality
control reference.
Draw an object schema that shows the relationship between the class
container and the derived classes carton and case.
3 A First Program

Objectives for this chapter


Familiarity with the c++ programming terms and concepts:
• the #include directive
• the keywords class, public and protected
• program comments
• function prototype, definition, heading, result type, arguments
• the resolution operator : :
• the keyword void
• the data type char and a text string
• the object cou t
• the function s trcpy
• the main function
• object class definition
• member data and member functions
• declaring an object as an instance of an object class
• calling member functions.
Ability to:
• understand a simple c++ program that uses a single object class
• understand the pseudo-code for a sequence
• write a simple C++ program based on the example in the chapter.

3.1 The model for our first program


Let us examine a simple program that displays a message on the monitor
screen. We need an object class that defines the contents of the message and at
least two functions. We need a function to give an initial value to the message
and a function to display the contents of the message. With a little thought we
could probably specify other functions such as determining the position on the
screen or defining the colour of the background and foreground for the
message. However, we will keep it simple and produce a model of the problem
in the form of an object class with just two functions, as shown in the object
schema given in figure 3.1.

21
22 Object Oriented Programming Using C++

Class : message f-- Identification

contents (of message) f-- Data

Initialise contents
r - Functions
Display contents

Figure3.!

3.2 The C++ code for our first program


Figure 3.2 contains the complete C++ code to display a message. Please accept
for the moment the necessity for what may appear to be many programming
statements for a straightforward task. The benefits of this approach will only
become apparent when we consider more complicated examples.
We will now explain this program line by line by repeating small parts of
the code with an explanation of the component parts.
The first two lines in our program are comments.
II HELLO.CPP
II A program to display the Hello World message
A comment is introduced by the two consecutive characters I I. Everything that
follows on that line is considered to be explanatory text that does not affect the
running of the program. Comments are ignored by the compiler and are
included to explain the program to a human reader. They can be placed
anywhere in a program, on lines by themselves as above, or towards the end of
a line containing a program statement. It is considered good programming
practice to include comments at the start of a program to explain its purpose. In
our case, we have the purpose preceded by the name of the file containing the
whole program.
Lines 3 and 4 are called include statements.
#include <iostream.h>
#include <string.h>
These lines are instructions to the compiler, known as directives. For the
moment we shall consider such statements as a means by which the compilation
system allows us to use certain of its features. In the first case, the way data is
sent to the monitor screen and read from the keyboard; the "io" is an
abbreviation for input and output and this statement enables us to use the object
cou t later in the program. In the second case, the way we may use groups of
A First Program 23

II HELLO.CPP
II A program to display the Hello World message
'include <iostream.h>
'include <string.h>
class message
(
public :
void initialise ()
void display ()
protected :
char contents [12]

void message: : initialise ()

strcpy (contents I "Hello World")


}

void message: : display ()

cout « contents « end!

void main ()

message hello ;
hello.initialise ()
hello. display ()
}

Figure 3.2

characters called strings; this statement enables us to use the function s trcpy
later in the program.
The section of code in lines 5 to 12 is a complete object class definition.
class message
{
public :
void initialise ()
void display ()
protected :
char contents [12]
} ;
24 Object Oriented Programming Using C++

The object class definition is introduced by the C++ keyword class followed
by the programmer-chosen class identifier message. The whole of the class
definition is bounded by braces { and }, and finally terminated by a semicolon.
Note that the layout of this section is not a necessary requirement of the C++
language, but indentation has been used to highlight the different component
parts.
Within the braces, we declare the functions and data associated with the
object class. We have two sections labelled by the C++ keywords public and
protected, note the colon that follows these keywords. We label parts of a
class definition in this way to enable or disable the general use of parts of an
object class. In general terms, those parts of an object class that are labelled
public may be used in any part of the program; those labelled protected
may only be used within the definition of the functions of the object class or its
descendants.
In the public part of the class definition, we have two function prototypes
called member function prototypes. These declare the object class functions.
In this case, functions to display and initialise a message. The format consists
of three parts: the result type, the identifier and the arguments. We will not
concern ourselves with the details of these parts other than in the context of
these simple examples. The result type here is void, meaning that the
functions do not produce anything that needs to be classified by type. The
programmer-chosen identifiers are display and initialise. The
arguments of a function are enclosed within parentheses. There are no
arguments for these functions, so we simply have the parentheses.
In the protected part of the class definition, we have the declaration of a
member data item:
char contents [12] ;
In this statement, we are declaring a text string to contain the contents of the
message. The keyword char introduces the declaration and defines the type of
data to be held, in this case characters. contents is the programmer-chosen
identifier for that part of memory where the string will be stored. [12] is the
maximum length of the string in characters. This includes an allowance of one
character to hold a special character to mark the end of the string. This is
necessary because text strings in C++ may vary in length up to the specified
maximum.
In lines 14 to 17 of the program we have the definition for the first of two
member functions.
void message: : initialise ()
{
strcpy (contents I "Hello World")
}
The first line of the function is its heading. This consists of the same three
parts as the associated prototype already described above. However, there are
A First Program 25

two differences. The programmer-chosen name initialise is preceded by


the object class identifier message followed by the scope resolution operator
: : . The technical details for this need not concern us at the moment; briefly, it
is needed so that the data defined in the class definition can be accessed within
the function. Notice also that there is no semicolon at the end of the function
heading, nor at the end after the closing brace.
The details of the function are enclosed within braces, we have just one
line that instructs the computer to make a copy of the text Hello World and
store that copy in the identifier contents. This line starts with strcpy
which is the name of a C++ function that does this. The words contents and
"Hello World" are called the arguments of the function strcpy and as
such are placed in parentheses after the function name. Note that arguments of
functions are separated by commas.
Lines 19 to 22 of the program contain the definition of the second
function.
void message: : display ()
{
cout « contents « end!

As with the previous function, the first line is the heading. Again, this
corresponds to the associated prototype with the inclusion of message: :.
Within the braces we have just one line that instructs the computer to
direct output to the monitor screen. This line starts with cou t, the name of an
object that has functions to achieve this. The output to be directed to the
monitor screen is specified by following cout with the operator « and a
definition of the output required. In this case we have two output definitions to
be handled by couto The first is the identifier contents; this indicates to
cou t that the string stored in this identifier is to be displayed on the monitor
screen. The second output definition is end! (an abbreviation for end of line);
this simply indicates to cou t that the current line must end and the screen
cursor is to be placed at the start of the next line.
Line 24 of our program is one that all of our programs will include (or one
very similar) to show where program execution begins.
void main ()
The parentheses indicate to the compiler that main is a function with no
arguments. The body of the main function is enclosed by braces (lines 25 and
29).
Line 26 is a declaration of the object hello as an instance of the class
message.
message hello ;
In effect, it makes a copy of all the members of message and gives them the
group identifier hello. This means that hello can be referred to within the
26 Object Oriented Programming Using C++

function main and that all the public parts of its class definition may be used.
We see this in the next two statements of the function (in lines 27 and 28).
hello. initialise () ;
The member function initialise for the object hello is called; this
means that the statement(s) within the function definition for initialise
are executed. Note the format, instance identifier then a full-stop (known as the
dot operator) then the member function identifier then the parentheses then a
semicolon. The result of the function being called will be that hello's copy of
contents will be given the value "Hello World". To see the way that this
is done, please refer again to the description of the function definition for
ini tialise of class message.
Finally, the display member function for the instance hello is called.
hello. display () ;
The result of this will be that the text stored in contents (that is, Hello
World) will be displayed on the monitor screen and the cursor placed at the
start of the next line. Again, to see the way that this is done, please refer to the
description of the function definition for display of class message.
Notice that the functions ini tialise and display were declared as
public because they are being used in the function main, which is outside
the definition of the object class. The string identifier contents was declared
as protected since it is only used within the definition of a member function
of the object class message.

3.3 Coding style


The layout of the program is of little concern to the compiler. Generally, spaces
are not significant. The use of spaces, comments and blank lines is left to the
discretion of the programmer. So, it is possible to produce a program that is
readily understood by the compiler but is not so easily read by the human
reader. You are encouraged to use a layout and style that ensure that your
programs are easy to follow and read.
The identifiers created by the programmer ate a matter of choice, but give
an opportunity to describe the data that is to be contained within them. Again,
you are encouraged to always use meaningful identifiers. Normally, an
identifier will not exceed 30 characters in length. It must start with either a
letter or the underscore character C) and its remaining characters may be
letters, digits or underscore characters.
Notice that the case used to write C++ is significant; for example,
strcpy is not the same as STRCPY. In our first program, we declared an
instance of message as hello, we could not then refer to it in the main
program by Hello.
Certain items of punctuation are mandatory parts of the C++ language. In
A First Program 27

our first program you will notice that declarations and statements end with a
semicolon. Also note that in lists, such as in the list of arguments of a function,
a comma is used to separate components.
C++ contains several keywords such as void, each of which has a
specific purpose. These keywords must be surrounded by one or more blank
characters and they must not be used as identifiers. The full list of C++
keywords is given in appendix C.

3.4 Pseudo-code for a sequence


As mentioned in section 1.7, a sequence using pseudo-code notation consists of
a number of statements to be executed presented in the order of execution.
Unless the components of a sequence are themselves controlling statements, the
statements will be in plain language with no formal syntax. However, we will
find that certain phrases tend to be used for like operations.
An example of a sequence using pseudo-code is given in figure 3.3. Here,
we show the basic actions of the function main from figure 3.2.

main
Declare object hello of type message
Call hello. initialise
Call hello.display

Figure 3.3

The first line identifies the function name. The next three are a sequence
of the actions to be performed in the order given.
A slightly more complex version of the function display could be described
in pseudo-code as in figure 3.4.

message: : display
Display screen headings
Display contents of message
Display screen footings

Figure 3.4

Here, the first line identifies the class and the function name. This is
followed by a sequence of three actions. Note that they are simply general
descriptions of the activities without relying on a formal syntax. The precise
details of what to display and where to display the data on the computer screen
would obviously need to be specified and implemented in the C++ code.
However, the generalisation 'display ... ' will suffice at the design stage.
28 Object Oriented Programming Using C++

3.5 Exercises
3.5.1 Please refer to the example in figure 3.2, then answer the following
questions:
(a) What is the purpose of lines I and 2? Ifthey were removed, what
effect would this have on the running of the program?
(b) Lines 3 and 4 permit the use of what C++ features?
(c) What do we call the program statements in lines 8 and 9? What do
we call the three component parts of each statement (excluding the
terminating semicolons)?
(d) What three things can you say about the data member declaration
in line 11?
(e) What are the differences between the function prototype in line 8
and the corresponding function heading in line 14.
(f) What does the member function ini tialise do?
(g) What does the member function display do?
(h) What is the point of line 24 (that is, void main ( ) )?
(i) What does the declaration in line 26 do?
(j) The member functions are called in lines 27 and 28. Describe each
of the four components of the statements (excluding the
terminating semicolon).
(k) What happens when a function is called?
(I) Name the five identifiers that are declared and then used in this
example? What are the C++ rules for making up identifiers?
(m) Why are the functions ini tialise and display declared as
public?
3.5.2 Make changes as necessary to the example in figure 3.2 to achieve the
following revised specification.
Allow for two messages to be displayed, the first should be
Hello all computer users
and the second
What a fine day!
You should implement this by making the first two lines more
appropriate, by replacing the member data declaration in the class
definition by two similar statements, and by replacing the single
statement in both of the member functions by two similar statements.
3.5.3 Please refer to section 3.4, then answer the following questions:
(a) What will the first line of the pseudo-code for a function normally
contain?
(b) Give an example of a pseudo-code statement indicating that a
function is to be used.
(c) Rewrite the pseudo-code for the display function so that the
actions are performed in the reverse order.
4 An Introduction to Inheritance

Objectives for this chapter


Familiarity with the C++ programming terms and concepts:
• the member function cin. qet
• the data type char for a single character
• program files and header files
• use of a prompt for keyboard input
• deriving a new object class from an existing (base) class
• using header files and a derived class
• inheriting object class members.
Ability to:
• understand a simple C++ program that uses a header file
• understand a simple C++ program that uses a derived object class
• write pseudo-code for a simple function
• write simple C++ programs based on the examples in the chapter.

4.1 Using a header file


Our first program in chapter 3 would normally be typed into a single computer
file and presented to the compiler for translation and execution to produce the
required results. However, we could separate the object class definition and
member function definitions from the function main. Let us say that we put the
defintions in a file called messaqe. h and the function main in the file called
hello_m.cpp. The file messaqe.h is known as a header file and its
contents are shown in figure 4.1. The contents of the program file,
hello_ m. cpp, are shown in figure 4.2.
In figure 4.2 we have the same main function as in figure 3.2 (in chapter
3), preceded by the #include statement referencing the header file. When we
present the program file to the compiler, as part of the translation process the
code from the header file, in effect, replaces the #include statement, in the
sense that the compiler now regards the program file as being exactly the same
as the first program in figure 3.2.
Note that in chapter 3 and figure 4.1 the previous #include statements

29
30 Object Oriented Programming Using C++

II MESSAGE.H
II The object class message
#include <iostream.h>
#include <string.h>
class message
{
public :
void initialise ()
void display ()
protected :
char contents [12]

void message::initialise ()

strcpy (contents I "Hello World")


}

void message: : display ( )

cout « contents « end!

Figure 4.1

II HELLO M.CPP
II A program to display the Hello World message
#include "message.h"
void main ()
{
message hello
hello.initialise ()
hello. display ()
}

Figure 4.2

reference facilities held in a compiler library and are identified by a name


enclosed in angle brackets <>; we now reference the message. h file and
enclose this name with ", to indicate that it is a file stored in the same directory
as the program file.
An Introduction to Inheritance 31

4.2 Inheriting code from onr first program into a second program
The statements in message. h can be reused in other programs that require
the object class message or derivatives based on it. For example, if we wished
to have an additional program that accepted any message from the keyboard
and then displayed it on the monitor screen, we have a similar model to that
described in figure 3. I, but need a different initialisation function. Instead of
simply assigning a value of "Hello World" to the contents of the
message, we need code to accept a string of characters into contents.
We could simply make a copy of message. h, call it a different name
and make modifications to the copy. However, there is a better solution to this
type of problem that avoids duplicating the code; rather it involves inheriting
the code from message. h by defining a new object class based on message,
but with a new member function ini tialise. Hence there is no code dupli-
cation, simply a replacement for that part which has different requirements.
The model of the new class any_message (the derived class) and its
derivation from the original class message (the base class) is represented by
the object schema shown in figure 4.3.

Class : message Derived class: any_message

contents (of message) .»-


Initialise contents Initialise contents
Display contents ~ _i.:.p_ll~:lill:"
V _ _ _ _·_ ..
:.·.:~;i(;_
i !:il _
Figure 4.3

As mentioned in chapter 2, notice how the arrows and shading indicate


those members of the derived class that have been inherited from the base class
without being changed; the lack of shading in the derived class indicates those
members that have been added or, in this case, redefined.
We implement this additional program by writing C++ code for a new
header file messagel. h and a new program file anymess. cpp. They are
shown in figures 4.4 and 4.5 respectively. The pseudo-code for the function
ini tialise is also given in figure 4.6.
Let us first describe the contents of the header file line by line.
II MESSAGE1.H
II The object class any_message
We have described comments before; these identify and reflect the purpose of
the new header file.
32 Object Oriented Programming Using C++

II MESSAGE1.H
II The object class any message
'include "message.h"
class any_message : public message
{
public :
void initialise ()

void any_message::initialise ()

char terminator ;
cout « "Enter message: "
cin.get (contents, 12)
cin.get (terminator) ;
}

Figure 4.4

II ANYMESS.CPP
II A program to display any message
'include "message1.h"
void main ()
{
any message do_message ;
do_message. initialise ()
do_message. display () ;
}

Figure 4.5

any_message::initialise
Declare terminator variable
Prompt for message
Accept message contents
Skip newline character

Figure 4.6

Line 3 is also familiar.


'include "message.h"
This statement is a directive to the compiler to take into account (or "include")
all the code found in the file message. h.
In lines 4 to 8, we define a new object class based on message as
An Introduction to Inheritance 33

previously defined in the file messaqe. h.


class any_messaqe : public messaqe
{
public :
void initialise ()
} ;
The first line in this section, introduced by the keyword class, specifies the
new object class, called any_messaqe, derived from the object class
messaqe with all of its facilities made public in the new class. Note the
colon after the new class identifier and before the derivation type public.
The new object class inherits all of the public and protected components of
the class upon which it is based. So we inherit the member data contents
and two member functions called initialise and display in our new
object class. However, we need to redefine the initialisation function, so we
declare a public member function ini tialise as part of any_messaqe;
as before, this is enclosed in braces.
In lines 10 to 16, we have the definition of the new member function
ini tialise.
void any_messaqe::initialise ()
{
char terminator ;
cout « "Enter messaqe: "
cin.qet (contents, 12)
cin.qet (terminator) ;
}

After the heading, we have four statements enclosed in braces as usual. The
first statement is a data declaration for a single character (indicated by the
keyword char). The function will refer to this area of data by the identifier
terminator. The second statement will display text on the monitor screen
inviting the user to type a message; this text is called a prompt. We have
already described the use of cou t to display data on the screen, in this case we
do not use end! because we want to keep the cursor on the same line. The
third statement will obtain the message from the keyboard. cin. qet is a
mechanism by which we can obtain, in this case, up to 11 characters from the
keyboard and store them in contents (with the end of string character being
automatically appended). Formally, qet is a member function of the object
cin provided by the compiler in iostream. h. The first argument of qet is
the identifier of an area to receive the data (con ten ts), the second is the
maximum length of the data (12) including the automatically appended end of
string character. It is assumed that after the data has been entered the user
presses the enter key. A side-effect of this is that the character generated when
the user presses enter (we will call it the newline character) is not transferred to
34 Object Oriented Programming Using C++

contents, and so to avoid it being used by mistake in some later processing,


we transfer it to another area called terminator. This is achieved by the
fourth statement using cin. get.
The main program, anymess. cpp given in figure 4.5, is very similar to
hello_m.cpp in figure 4.2. It has the same structure but references a
different header file and uses different identifiers. The differences are now
described.
In line 3 we have a different include statement.
#include "messagel.h"
The new header file is referenced (instead of message. h), but note that
messagel. h does, in turn, reference message. h.
The 3 statements of the function main refer to the derived class
any_message.
any_message do_message ;
do_message. initialise ()
do_message. display () ;
Here, we have the declaration of an instance of the new object class
any_message called do_message. Then we have the two member function
calls. The first invokes the new initialise function to prompt for and
receive the data. The second calls the inherited display function.
It is important to appreciate the relationship between the model in figure
4.3 and the three files that are used in the complete program. The base class
message is defined in message. h (figure 4.1). The file messagel. h
(figure 4.4) uses a #include statement to incorporate message.h and
defines the derived class any_message, which inherits the members of
message, but has a different, overriding, initialise function. The
program file anymess. cpp (figure 4.5) uses a #include statement to
incorporate messagel. h and contains the executable code based on an object
do_message of the class any_message.

4.3 Exercises
4.3.1 Please refer to the program in figures 4.1 and 4.2, then answer the
following questions:
(a) What is the difference between the two #include statements in
the header file message. h and the one in the program file
hello_m.cpp?
(b) What is the purpose of the UncI ude statement in the program
file hello_ m. cpp?
4.3.2 Please refer to the examples in figures 4.4 and 4.5, then answer the
following questions:
An Introduction to Inheritance 35

(a) Why is line 3 (the #include statement) included in the header


file messagel. h?
(b) The first line of the class definition in the header file
messagel. h consists of four words as well as the colon. What is
the purpose of each of the four words?
(c) How do you declare a data area for a single character?
(d) The cout statement in the header file messagel. h does not
have an end!, can you suggest why?
(e) What is the purpose ofthe first cin. get statement? Why does the
cin. get function have 12 as an argument when contents will
be of a maximum size of 11 ?
(f) What is the purpose of the second cin. get statement? Why is it
necessary?
(g) How does the compiler know which ini tialise member
function to use, the one in message. h or the one in
messagel. h.

4.3.3 Describe what changes are necessary to the program in figures 4.1 and
4.2 to achieve the following revised specification.
Allow for two messages to be displayed, the first should be
Hello all computer users
and the second
What a fine day!
You should replace the member data statement in the class definition
by two similar statements, and replace the statement in each of the
member functions by two similar statements.
4.3.4 Describe what changes are necessary to the program in figures 4.4 and
4.5 to achieve the following revised specification.
Allow for two messages to be displayed, the first should be
Hello boys
and the second
Hello girls
You should implement this by amending the program file
anymess . cpp only.

4.3.5 Produce a new header file forename. h (inheriting message from


message. h) and a new program file assign45. cpp to achieve the
following specification.
Prompt the user of the program to enter their forename, accept the
forename from the keyboard, then display it back on the screen. You
may assume that the forename will contain at most 11 characters.
Before writing the c++ code, produce pseudo-code for the function
ini tialise, a member of the class forename.
5 Arithmetic

Objectives for this chapter


Familiarity with the C++ programming terms and concepts:
• the data types int, lonq int and float
• the keyword cons t
• the arithmetic operators + - * / % ++
• the precedence of arithmetic operators
• integer and float variable declarations
• assignment statements that use arithmetic expressions
• cin and cout with int and float values
• the manipulator setprecision.
Ability to:
• develop an object class definition
• use a model and pseudo-code descriptions of the functions of an object
class to produce C++ code
• read and understand a simple C++ program that uses integer and real
numbers
• write simple C++ programs that use integer and real numbers.

5.1 Integers
In C++ every item of data is considered to be of a specific type. For example,
numbers such as 4 and 37 are examples of integers, whereas 6.75 and 2.5 are
examples of real numbers. Different data types are stored and manipulated
differently within the machine. Consequently, we must define the type of each
identifier whenever we declare it in a program.
We can declare the member data for an object class or variables within a
function by specifYing a type and an identifier (such as char terminator
in the function ini tialise referred to in the previous chapter). To declare
integer member data or variables, we use the type name int followed by an
appropriate identifier and a semicolon, for example
int years_of_aqe ;
A value of type int is a whole number lying within limits defined by the

36
Arithmetic 37

compiler. The minimum and maximum integer values for typical C++ systems
are -32768 to 32767. The values of all integer data items must lie within
these limits.
If a larger range is required, then one can use the type long int (this
can be abbreviated to long) which typically has a range of -2147483648 to
2147483647. Other integer types are also available.

5.2 Assignment statements and integer arithmetic


In the previous chapter, we used the function strcpy to store a string value in
the variable identifier contents using
strcpy (contents, "Hello World") ;
For other data types, including integers, a value is copied into a storage
location by means of an assignment statement. In its simplest form an
assignment statement consists of a variable identifier followed by the assign-
ment operator = followed by an expression that will give a value to be placed in
the variable. For example,
average_age = total_age / no_of_people ;
The result of this assignment statement would be that a new value is given to
the data item identified by average_age. The / symbol is used to denote
division. The full range of arithmetic operators used in integer expressions is
given in the table in figure 5.1.

Operator Meaning
++ increase by 1
-- decrease by 1

* multiply
/ divide
% give remainder after division
+ add
- subtract or ne~ate
Figure 5.1

Integer division produces a truncated result (not rounded up or down). For


example,
average_age = 124 / 5 ;
assigns the value 24 to average_age.
38 Object Oriented Programming Using C++

The % operator
gives the remainder after division. For example,
left_over = 124 % 5 ;
assigns the value 4 to left_over.
The ++ and - - operators allow a shorthand for increasing and decreasing
by one. For example,
++ counter ;
increases the value already in counter by 1.
When an arithmetic expression involving sub-expressions is evaluated, the
normal priorities (precedence) of the above operators apply. Any sub-expression
in parentheses is evaluated first, then ++ and - - have priority over *, / and %,
which, in turn, have priority over + and -. When two operators of the same
priority are contained within an expression, evaluation is from left to right. The
full list of C++ operators in order of precedence is given in appendix C.
Notice that the spaces either side of the operators are optional, but are
included to aid readability.

5.3 Real arithmetic


If we want to use real numbers such as 23.75 or 0.5, we use the data type
float. As with integers we can declare float member data in class
definitions or variables in functions. For example,
float unit_price,
total_cost ;
Each C++ system defines limits on the range (the smallest and largest
allowable values) and precision (the maximum number of significant digits) of
numbers of type float. Any attempt to evaluate a value outside the given
range results in overflow (the result is too large) or underflow (the result is too
small). For very large or very small real numbers, we use the type double.
We use the same basic operators in real expressions that we have already
seen in integer expressions except for the % operator that obviously has an
application only with integers.
C++ allows you to mix integers and real numbers in arithmetic
expressions. As each part of the expression is evaluated, if both operands are
integers, the resulting value will be of type in t; but if either or both of the
operands are real numbers, the resulting value will be of type float.

5.4 A model for a student's assessment in a subject


A program is required to process a single student's examination mark and
practical mark for a single module. The module identity, student identity,
examination mark and practical mark will be obtained from the keyboard, then
Other documents randomly have
different content
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like