Object Oriented Programming Using C An Introduction 1st Edition by Pardoe, King 0333692411 978-0333692417instant download
Object Oriented Programming Using C An Introduction 1st Edition by Pardoe, King 0333692411 978-0333692417instant download
https://ebookball.com/product/object-oriented-programming-using-
c-an-introduction-1st-edition-by-pardoe-
king-0333692411-978-0333692417-15282/
https://ebookball.com/product/object-oriented-programming-
using-c-1st-edition-by-simon-kendal-9788776818142-15260/
https://ebookball.com/product/beginning-c-3-0-an-introduction-to-
object-oriented-programming-1st-edition-by-jack-
purdum-0470261293-978-0470261293-15238/
https://ebookball.com/product/microsoft-visual-c-2017-an-
introduction-to-object-oriented-programming-7th-edition-by-joyce-
farrell-isbn-1337102100-9781337102100-25038/
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/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-17244/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15256/
https://ebookball.com/product/an-introduction-to-object-oriented-
programming-with-java-5th-edition-by-thomas-
wu-0073523305-9780073523309-15330/
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
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
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
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
Index 249
Preface
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.
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
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
to its right as byte 01 and the one directly beneath it as byte 10, and so on.
9 I I
Figure 1.2
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.
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.
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.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
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.
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.
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
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++
name
date of birth
qualifications
telephone number
etc ..
Amend qualifications
Get telephone number
Calculate age
Display details
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.
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++
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
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++
21
22 Object Oriented Programming Using C++
Initialise contents
r - Functions
Display contents
Figure3.!
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 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
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.
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.
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
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 ()
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
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.
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
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++
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
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.
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.
Operator Meaning
++ increase by 1
-- decrease by 1
* multiply
/ divide
% give remainder after division
+ add
- subtract or ne~ate
Figure 5.1
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.
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
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.
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.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookball.com