Sunteți pe pagina 1din 266

C++ for Physics

Oxford University
Computing Services
How to Use this User Guide
 This handbook accompanies the taught sessions for the course. Each
section contains a brief overview of a topic for your reference and
then one or more exercises.
 Exercises are arranged as follows:
 A title and brief overview of the tasks to be carried out;
 A numbered set of tasks, together with a brief description of each;
 A numbered set of detailed steps that will achieve each task.
 Some exercises, particularly those within the same section, assume that
you have completed earlier exercises. Your teacher will direct you to
the location of files that are needed for the exercises. If you have any
problems with the text or the exercises, please ask the teacher or one
of the demonstrators for help.
 A number of conventions are used to help you to be clear about what you
need to do in each step of a task.
 In general, the word press indicates you need to press a key on the
keyboard. Click, choose or select refer to using the mouse and
clicking on items on the screen.
 Names of keys on the keyboard are enclosed in angle brackets; for
example <ENTER> represents the Enter (or Return) key.
 Multiple key names enclosed in angle brackets and linked by a + (for
example, <CTRL+Z>) indicate that the first key should be held down
while the remaining keys are pressed; all keys can then be released
together.
 Where two or more keys are each enclosed in separate angle brackets (for
example, <HOME><HOME><UP ARROW>) each key in the sequence
should be pressed in turn.
 Words and commands typed in by the user are shown like this.
 Labels and titles on the screen and button names are shown l i k e t h i s .
 Drop-down menu options are indicated by the name of the option
enclosed in square brackets, for example F i l e | P r i n t . To select the
option P r i n t from the F i l e menu: click with the mouse button on the
F i l e menu name; move the cursor to P r i n t ; when P r i n t is
highlighted, click the mouse button again.
 A button to be clicked will look l i k e t h i s .
 The names of software packages are identified like this, and the names of
files to be used l i k e t h i s .

OUCS ii November 2008


Software Used
Eclipse

Files Used in Session 1


These are available from:
http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013/EclipseStudentFiles_part1.tgz
Array.cpp InsertionSort.h
Array.dev LinearSearch.cpp
CharNumString.cpp LinearSearch.dev
CharNumString.dev MultiDimArrayMain.cpp
CharNumStringFunc.cpp OverLoadingFunctions.cpp
CharNumStringFunc.dev OverLoadingFunctions.dev
constructor.txt PointerArithmetic.dev
DoWhile.dev PointerArithmeticMain.cpp
DoWhile.h Pointers.dev
DoWhilemain.cpp PointersMain.cpp
FunctionTemplate.dev StudentMarksInterface.h
FunctionTemplate-Maximum.cpp StudentUG.txt
FunctionTemplate-Maximum.h TemperaturesRetValues.cpp
GetSet.txt TemperaturesRetValues.dev
Header.cpp Vector.cpp
Header.dev Vector.dev
If.dev Vector.txt
IfMain.cpp While.dev
IfSwitch.cpp While.h
IfSwitch.dev WhileMain.cpp
IfSwitch.h

Revision Information

Version Date Author Changes made


1.0 26 November 2008 Ian Miller Created
1.1 28 November 2013 Sean Brisbane Updated to use
Eclipse IDE

Copyright
The copyright of this document lies with Oxford University Computing Services.

November 2008 iii OUCS


Contents
1 INTRODUCTION........................................................................................................1
1.1. What you should already know.......................................................................................................................1

1.2. What you will learn..........................................................................................................................................1

1.3. Where can I get a copy?...................................................................................................................................2

2 THINGS TO UNDERSTAND......................................................................................3
2.1. Compilers, new and old...................................................................................................................................3

3 OBJECT ORIENTED PROGRAMMING (OOP)........................................................4


3.1. Object Oriented programming Concepts......................................................................................................4

4 SETTING UP THE ENVIRONMENT..........................................................................5


4.1. IDE choice.........................................................................................................................................................5

4.2. Dev-C++............................................................................................................................................................5
Exercise 1 Installing Dev-C++.......................................................................................................................6

4.3. Configuring the Eclipse workspace..............................................................................................................12


Exercise 1 Importing project skeletons into eclipse...........................................................................................13

5 CREATING YOUR FIRST PROGRAM....................................................................20


5.1. IDE choice.......................................................................................................................................................20

5.2. Creating your first program in Dev-C++.....................................................................................................20


Exercise 2 Creating a first program.............................................................................................................21

5.3. Creating your first program in eclipse.........................................................................................................23


Exercise 2 Creating a first program in eclipse...................................................................................................23

5.4. What does this first C++ program do?.........................................................................................................26


Exercise 3 Modify the program...................................................................................................................28

5.5. Arithmetic Operators.....................................................................................................................................30

5.6. Characters.......................................................................................................................................................30

5.7. Strings.............................................................................................................................................................31

5.8. Casts................................................................................................................................................................32
Exercise 4 Create additional projects...........................................................................................................34

6 INTRODUCTION TO FUNCTIONS..........................................................................37
6.1. Creating a function........................................................................................................................................37
Exercise 5 Examining a function.................................................................................................................38

OUCS iv November 2008


Exercise 6 Writing functions........................................................................................................................41

6.2. Functions and Pass by Reference..................................................................................................................44


Exercise 7 Pass arguments by reference......................................................................................................45

7 CLASSES AND OBJECTS......................................................................................47


7.1. Creating your first class.................................................................................................................................48
Exercise 8 Creating a class...........................................................................................................................48

7.2. Member functions and Passing parameters................................................................................................50


Exercise 9 Passing parameters.....................................................................................................................50

7.3. Data Members................................................................................................................................................50


Exercise 10 Using data members...................................................................................................................51
Exercise 11 More Objects..............................................................................................................................52

7.4. Constructors...................................................................................................................................................53
Exercise 12 Using constructors......................................................................................................................54

7.5. Destructors......................................................................................................................................................55

7.6. Separate Class Files for Reusability.............................................................................................................57


Exercise 13 Using header files.......................................................................................................................57

8 BASIC CONTROL FLOW........................................................................................61


8.1. Selection - if…else statement.........................................................................................................................61
Exercise 14 if …else selection.......................................................................................................................62

8.2. Selection - switch multiple selection statement............................................................................................64


Exercise 15 switch selection..........................................................................................................................64

8.3. Repetition – while, do…while and for loops................................................................................................68


Exercise 16 while loop...................................................................................................................................68
Exercise 17 for loop.......................................................................................................................................72
Exercise 18 do…while loop...........................................................................................................................73

9 ARRAYS, VECTORS AND LISTS...........................................................................74


9.1. Declaring and using arrays...........................................................................................................................74
Exercise 19 Creating an array to hold exam results.......................................................................................75

9.2. Searching Arrays with Linear Search..........................................................................................................78


Exercise 20 Linear Search..............................................................................................................................78

9.3. Sorting Arrays with Insertion Sort...............................................................................................................81


Exercise 21 Sorting an array..........................................................................................................................81

9.4. Multidimensional Arrays...............................................................................................................................83


Exercise 22 Creating a multidimensional array.............................................................................................84

9.5. Declaring and using vectors..........................................................................................................................87


Exercise 23 Creating a vector to hold exam results.......................................................................................88
Exercise 24 Create a vector of objects...........................................................................................................91
Exercise 25 Using the insert() member function and iterators.......................................................................92

November 2008 v OUCS


9.6. Declaring and using lists................................................................................................................................94
Exercise 26 Merging lists...............................................................................................................................95

10 MORE ON FUNCTIONS........................................................................................98
10.1. Multiple arguments and default values......................................................................................................98
Exercise 27 Functions with multiple arguments and default values..............................................................98

10.2. Returning values from functions................................................................................................................99


Exercise 28 Returning a value from a function............................................................................................100
Exercise 29 Classes and functions...............................................................................................................102

10.3. Passing Arrays to Functions......................................................................................................................103


Exercise 30 Passing Arrays to functions......................................................................................................103

10.4. Passing Two-dimensional Arrays to Functions........................................................................................106


Exercise 31 Multi-Dimensional Arrays and functions.................................................................................106

10.5. Overloading functions................................................................................................................................109


Exercise 32 Function Overloading...............................................................................................................109

10.6. Function Templates....................................................................................................................................112


Exercise 33 Function Templates...................................................................................................................112

11 POINTERS...........................................................................................................115
11.1. Initialising pointers.....................................................................................................................................115
Exercise 34 Using pointers...........................................................................................................................116

11.2. Pointer Arithmetic and Arrays..................................................................................................................117


Exercise 35 Pointers and Arrays..................................................................................................................118

12 CLASSES AND INTERFACES............................................................................122


12.1. Interfaces.....................................................................................................................................................122
Exercise 36 Creating an Interface................................................................................................................122

13 SESSION 2..........................................................................................................125
13.1. files used......................................................................................................................................................125

14 INLINE FUNCTIONS, VALUES AND REFERENCES........................................126


14.1. Inline functions...........................................................................................................................................126

14.2. Functions, call by reference and call by value.........................................................................................126


Exercise 37 Examine inline functions and call by reference.......................................................................127

14.3. Reference parameters and classes............................................................................................................130


Exercise 38 Examine and modify class reference parameters.....................................................................131

14.4. Constant objects and const member functions........................................................................................132


Exercise 39 Modify constant pointers and references.................................................................................134

15 MORE ON CLASSES..........................................................................................135

OUCS vi November 2008


15.1. Inheritance..................................................................................................................................................135

15.2. Inheritance Syntax.....................................................................................................................................136

15.3. Public, Private or Protected?....................................................................................................................137


Exercise 40 Base and Derived classes.........................................................................................................138

15.4. Member initialiser list................................................................................................................................142


Exercise 41 Using an initialiser list..............................................................................................................142

15.5. Preprocessor wrappper #indef..................................................................................................................144


Exercise 42 Add a preprocessor wrapper.....................................................................................................144
Exercise 43 Adding an additional class.......................................................................................................145

15.6. Overriding base class methods..................................................................................................................146


Exercise 44 Overriding Base Class Methods...............................................................................................146
Exercise 45 Human Inheritance...................................................................................................................148

15.7. Friends and Functions...............................................................................................................................150


Exercise 46 Examine a friend function........................................................................................................150
Exercise 47 Add a friend function...............................................................................................................152

15.8. Friends and Classes....................................................................................................................................153


Exercise 48 Using friend classes..................................................................................................................153
Exercise 49 Adding a friend class................................................................................................................155

15.9. Composition................................................................................................................................................156
Exercise 50 Composition, using objects as members of other classes.........................................................156
Exercise 51 Composition, dates as object members of student class...........................................................160
Exercise 52 Composition, Starting the OUCS ATM....................................................................................161

16 OPERATOR OVERLOADING.............................................................................162
16.1. Overload + operator...................................................................................................................................162
Exercise 53 Overloading the addition operator +........................................................................................162

16.2. Overload stream operators........................................................................................................................165


Exercise 54 Overloading stream insertion operators...................................................................................165

17 DYNAMIC MEMORY ALLOCATION...................................................................169


17.1. Dynamic Cats..............................................................................................................................................170
Exercise 55 Dynamic memory allocation and pointers...............................................................................170
Exercise 56 Dynamic arrays........................................................................................................................171

18 POINTER-BASED STRING PROCESSING........................................................172


18.1. Characters and Pointer-Based strings......................................................................................................172

18.2. String manipulation Functions.................................................................................................................173


Exercise 57 Copying, concatenating and tokenising strings........................................................................173
Exercise 58 Use string manipulation functions to modify a program..........................................................177
Exercise 59 Using string manipulation functions........................................................................................178

19 POLYMORPHISM................................................................................................179
19.1. Polymorphism.............................................................................................................................................180

November 2008 vii OUCS


Exercise 60 How polymorphism works.......................................................................................................180
Exercise 61 Accessing non-virtual member functions.................................................................................184
Exercise 62 Implement polymorphism........................................................................................................185

20 SESSION 3..........................................................................................................187
20.1. files used......................................................................................................................................................187

21 ABSTRACT CLASSES........................................................................................188
21.1. Examining an Abstract Class....................................................................................................................189
Exercise 63 Abstract classes & dynamic binding........................................................................................189
Exercise 64 Create a new Abstract class......................................................................................................193
Exercise 65 ATM, base class pointers and private utility functions............................................................194

22 COMPLETING THE OUCS ATM.........................................................................197


Exercise 66 OUCS ATM class diagram.......................................................................................................197

23 THE STANDARD TEMPLATE LIBRARY............................................................199


23.1. Containers...................................................................................................................................................199

23.2. Common member functions for all containers........................................................................................200

23.3. Algorithms...................................................................................................................................................201

23.4. Introduction to iterators............................................................................................................................203

23.5. Member Functions by Container..............................................................................................................207

23.6. Reading and writing files...........................................................................................................................208


Exercise 67 Using files to add data to containers........................................................................................210

23.7. Using the vector class container................................................................................................................212


Exercise 68 Vectors, iterators and algorithms..............................................................................................213
Exercise 69 Calculating the min, max and mean of vector elements..........................................................216

23.8. Using the list class container.....................................................................................................................218


Exercise 70 Using the list container.............................................................................................................218

23.9. Using the deque class container................................................................................................................225


Exercise 71 Using the deque container........................................................................................................226

23.10. Using the multiset associative container................................................................................................229


Exercise 72 Using the multiset container.....................................................................................................229

23.11. Using the multimap associative container..............................................................................................234


Exercise 73 Using the mutimap container...................................................................................................235

23.12. More on using algorithms........................................................................................................................239

24 APPENDIX...........................................................................................................240
24.1. Arithmetical Operators..............................................................................................................................240

24.2. Assignment Operators...............................................................................................................................240

OUCS viii November 2008


24.3. Assignment and Arithmetic examples......................................................................................................240

24.4. Relational and Equality Operators..........................................................................................................241

24.5. Logical Operators......................................................................................................................................242

24.6. Escape Sequences.......................................................................................................................................242

24.7. Cast Operator.............................................................................................................................................243

24.8. Formatted Output......................................................................................................................................243

24.9. Header Files................................................................................................................................................243

24.10. Scope..........................................................................................................................................................244

24.11. Enumerating constants............................................................................................................................244

24.12. Constants...................................................................................................................................................244

24.13. Vectors member functions.......................................................................................................................245

24.14. Container global functions......................................................................................................................245

24.15. cmath functions........................................................................................................................................246

24.16. String class................................................................................................................................................246

24.17. Pointer based String Manipulation Functions......................................................................................248

24.18. Constant Objects and const Member functions....................................................................................249

24.19. ASCII Character set...................................................................................................................................250

November 2008 ix OUCS


C++ DPFE

1 Introduction
Welcome to the C++ for Physics course.
This booklet accompanies the course delivered by Oxford University Computing
Services (OUCS), IT Learning Programme. Although the exercises are clearly
explained so that you can work through them yourselves, you will find that it will
help if you also attend the taught session where you can get advice from the
teachers, demonstrators and even each other!
If at any time you are not clear about any aspect of the course, please make sure
you ask your teacher or demonstrator for some help. If you are away from the
class, you can get help by email from your teacher or from help@oucs.ox.ac.uk.

1.1. What you should already know


There is no prerequisite for this course. Having some programming knowledge
will be helpful but the documentation is structured such that those new to
programming will be able to follow the course at a pace suitable to them.
The computer network in OUCS may differ slightly to what you are used to in
your College or Department; if you are confused by the differences ask for help
from the teacher or demonstrators.

1.2. What you will learn

Session 1 Session 2 Session 3


Working with Dev-C++; Inline functions; STL
Creating first programs; Call by reference and value; Iterators
Fundamental data types, Inheritance; Vector container
strings, casts;
Classes and objects; Public, Private and Protected List container
data;
Attributes and behaviours; Base and derived classes; Deque container
Member functions; Preprocessor wrapper Multiset container
#indef;
Constructors; Overriding functions; Multimap container
Destructors; Friend functions; Algorithms
Control Flow Friend classes;
Functions Composition;
Arrays and Vectors Dynamic memory allocation
and pointers;
Header Files Pointer based string
processing;
Interfaces String manipulation
functions;
Operator overloading;

November 2013 1 OUCS


DPFE C++

Polymorphism;
Virtual member functions;
Pure virtual member
functions;
Abstract classes;

1.3. Where can I get a copy?


In this course you will be using the g++ compiler and the “eclipse” development
environment. This is freely available on all OSX, Linux and Windows systems. It
can be downloaded from http://www.eclipse.org/.

Physics/ITLP 2 November 2013


C++ DPFE

2 Things to understand

2.1. Compilers, new and old


Not all C++ compilers comply with the official ISO C++ standard which was
published in 1998. For detailed information on which compilers support the
standard see http://www.cuj.com/documents/s=8193/cuj0104sutter/.
What does this mean? It means the code you write, compile and run on one
machine may not compile on the next machine (even if it is using the same
operating system) if you are using a different compiler.
In this course you will be using the g++ compiler and the “eclipse” development
environment. This is freely available on all OSX, Linux and Windows systems. It
can be downloaded from http://www.eclipse.org/.
Some older header files you may see with inherited C++ code are:
#include <iostream.h> have a .h extension. The C++ standard for this header
file is #include <iostream>. Your program may run correctly by adding a .h, but
simply adding a .h suffix will not work for all included files.
#include <string.h> has been replaced with #include <string>. The string.h
header file does not include C++ strings, it includes C strings.
#include <math.h> has been replaced with #include <math>.
The lesson to be learnt here is that a lot of C++ code you come across will have
been created on older compilers. Some of the header and other code will not be
recognised and may cause compilation errors when compiled on a machine which
is more compliant with the C++ standard.

November 2013 3 OUCS


DPFE C++

3 Object Oriented Programming (OOP)


3.1. Object Oriented programming Concepts
C++ is an object oriented programming (OOP) language. This means in the
programs you create you will work with real world objects. Common objects are
people, planes, cars, buildings, birds and many more.
There are many other objects that you see and interact with each day. The objects
you use in C++ will be created (instantiated) from the class code you write.
Classes contain f u n c t i o n s that implement operations and d a t a that implements
attributes.
Real world object and class objects share two characteristics: They both have a
s t a t e and b e h a v i o u r . For example, cars have a s t a t e (speed, number of wheels,
number of seats, colour) and b e h a v i o u r (moving, stopped, braking, accelerating,
slowing down, changing gear).
Class objects are modelled after real-world objects so they too have s t a t e and
b e h a v i o u r . A software object maintains its s t a t e in one or more v a r i a b l e s
where data is stored. A v a r i a b l e is an item of data named by an identifier. A
software object implements its b e h a v i o u r with member functions. A member
function is a subroutine and is always associated with an object.
Languages like C are procedural and the programming tends to be action
oriented. C programs are written using functions that contain the code to
implement certain actions or tasks.
In C++ we work with c l a s s e s and o b j e c t s . So, what is the relationship between
a class and an object? To build a house you need a plan of the proposed layout.
You can build many houses from the one plan. If you have a house c l a s s then it
is possible to instantiate (create) many o b j e c t s of the house class. Classes can
also have relationships with other classes. There may be associations between the
house class, a builder class, a surveyor class, a buyer class and others.
In OOP it is possible to define classes in terms of other classes. For example,
Jaguar X-Type, Mazda RX3, Bentley, Ford Focus are all kinds of car. In object-
oriented terminology, Jaguar X-Type, Mazda RX3, Bentley, Ford Focus are all
s u b c l a s s e s of the car class. Similarly, the c a r class is the s u p e r c l a s s of
Jaguar X-Type, Mazda RX3, Bentley, Ford Focus.
Each subclass i n h e r i t s the states (variables) and behaviours (functions) from the
superclass. This means the subclass automatically contains the variables defined
in their superclass. The subclass members Jaguar X-Type, Mazda RX3, Bentley,
Ford Focus share the states: number of seats, colour etc of the superclass.
Each subclass also i n h e r i t s member functions from the superclass. Jaguar X-
Type, Mazda RX3, Bentley, Ford Focus will share some behaviours of the
superclass. Braking, accelerating and changing gear are possible examples.
However, subclasses are not limited to the state and behaviours provided to them
by their superclass. Subclasses can add variables and functions (sometimes
called methods) to the ones they inherit from the superclass. It is common
practice to define common behaviours in superclasses and fill in specific details
with specialised subclasses.

Physics/ITLP 4 November 2013


C++ DPFE

4 Setting up the environment


4.1. IDE choice
If you are using Mac OSX or Linux to complete this workbook, skip the Dev-C++
secion and go to the eclipse section.
On Windows, read the Dev-C++ section and skip the eclipse section.

4.2. Dev-C++
What is Dev-C++? Dev-C++ is a freely available C++ compiler.
One thing is for sure, we speak a different language from computers and there is
no way a computer cannot understand the spoken or written language we use in
our daily conversations. To make matters worse we do not understand the binary
language that our computers use to perform complicated tasks. This suggests we
have a communication problem.
So what is a compiler and how can it help? The compiler is a tool that allows us
to write instructions in some specially defined language (unfortunately not
English, yet) in our case C++, which us humans can understand. This is called
the s o u r c e code (a high level language code). The compiler then converts this
precise language (C++) into a concise language that the computer can understand
called o b j e c t code (a low level language code). This object code will most likely
be used by other programs in the process of creating a working program.

November 2013 5 OUCS


DPFE C++

Exercise 1 Installing Dev-C++


 Install Dev-C++

Task 1 Step 1
Install Dev-C++ Using Windows Explorer or My Computer navigate to
the H : \ d r i v e and double click on the program
d e v c p p - 4 . 9 . 9 . 2 _ s e t u p . e x e , see Figure 1.

Figure 1

Step 2

Click O K when you see the installation window


prompt shown in Figure 2.

Figure 2

Physics/ITLP 6 November 2013


C++ DPFE

Step 3

From the I n s t a l l e r L a n g u a g e window select


E n g l i s h (or a language of your choice) then click O K .
See Figure 3.

Figure 3

Step 4
Click the I A g r e e button when you get to the License
Agreement window, see Figure 4.

Figure 4

November 2013 7 OUCS


DPFE C++

Step 5
Click on N e x t when you see the Choose Components
window, see Figure 5.

Figure 5

Step 6
Click the I n s t a l l button at the Choose Install
Location window. See Figure 6.

Figure 6

Physics/ITLP 8 November 2013


C++ DPFE

Step 7
Click on the Y e s button at the prompt shown in
Figure 7.

Figure 7

Step 8
To complete the installation click F i n i s h , see Figure
8.

Figure 8

Step 9
At the Beta version Notice click O K , see Figure 9

Figure 9

November 2013 9 OUCS


DPFE C++

Step 10
When you see the D e v - C + + f i r s t t i m e
c o n f i g u r a t i o n window (Figure 10) click the
> N e x t button.

Figure 10

Step 11
Make sure Y e s , I w a n t t o u s e t h i s f e a t u r e is
selected then select the > N e x t button to select
additional features, see Figure 11.

Figure 11

Physics/ITLP 10 November 2013


C++ DPFE

Step 12
To create the code completion cache click the
> N e x t button, see Figure 12.

Figure 12

Step 13
Dev-C++ should now be successfully configured, see
Figure 13. If you do NOT see this window, speak to
the teacher or one of the demonstrators. Select  O K .

Figure 13

November 2013 11 OUCS


DPFE C++

Step 14
Close the T i p o f t h e d a y window by clicking the
C l o s e button, see Figure 14.

Figure 14

Step 15
Dev-C++ installation has finished and you are now
ready to write you first program. Instructions on how
to do this are in Section 5.2

Figure 15

4.3. Configuring the Eclipse workspace


Partly completed projects
Many of the projects are given as partly completed skeleton projects to save time. The
following instructions show you how to the projects that will be used over the course
of the day.

Physics/ITLP 12 November 2013


C++ DPFE

Exercise 1 Importing project skeletons into eclipse


 Open eclipse
 Import projects

Task 1 Step 1

Launch eclipse OSX machines, select the "l a u n c h p a d " from the
taskbar

Step 2

Figure 16

and start typing "eclipse"

Figure 17

Step 1

On Scientific Linux machines, run "eclipse" from


the command line.

November 2013 13 OUCS


DPFE C++

Task 2
Choose a workspace Choose a new workspace

We will split the work into three sessions. Name


the new workspace "w o r k s p a c e _ p a r t 1 " in the
Documents sub directory of your home directory.

Figure 18

Task 3
Download the Step 1
materials for the
session from the web. Download the required materials from the web.
These are currently These are located at
located at:
Part 1: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013
/EclipseStudentFiles_part1.tgz

Part 2: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013
/EclipseStudentFiles_part2.tgz

Part 3: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus
_2013/EclipseStudentFiles_part3.tgz

Physics/ITLP 14 November 2013


C++ DPFE

Task 4
Import the first part into Import the project skeletons into your
your project workspace workspace
Select F i l e = > I m p o r t

Figure 19

November 2013 15 OUCS


DPFE C++

Task 5 Choose to “import an existing project into the


Select the existing workspace”. Do not select the “Archive File”
project option option.

Figure 20

Physics/ITLP 16 November 2013


C++ DPFE

Task 6 On the next page, the type is archive file.


Import the tar file you Browse to the directory of files that you unpacked
have just downloaded in in Error: Reference source not found.
Error: Reference source Within that directory is another archive
not found ProjectsSkel.tar.
All projects within the archive should
automatically be detected and ticked.

Figure 21

November 2013 17 OUCS


DPFE C++

Task 7 After editing projects, they should be built and


Build and run the project run. Initially, select build project from the project
menu.

Figure 22

Task 8
To run the project, and
for each subsequent
build + run cycle, just See Error: Reference source not found on the next page
select the green play
button.
See Error: Reference
source not found on
the next page

Physics/ITLP 18 November 2013


C++ DPFE

Figure 23

November 2013 19 OUCS


DPFE C++

5 Creating your first program


5.1. IDE choice
If you are using Mac OSX or Linux to complete this workbook, skip the Dev-C++
secion and go to the eclipse section.
On Windows, read the Dev-C++ section and skip the eclipse section.

5.2. Creating your first program in Dev-C++

Physics/ITLP 20 November 2013


C++ DPFE

Exercise 2 Creating a first program


 Open Dev-C++
 Add a first program

Task 1 Step 1
Create your first If Dev-C++ is not already running, open the program
program.
by double clicking on the icon in the N A L
window or select S t a r t | A l l P r o g r a m s |
Bloodshed Dev-C++ | Dev-C++ .

Select F i l e | N e w | p r o j e c t . The dialog box shown


in Figure 24 appears.

Figure 24

Select C o n s o l e A p p l i c a t i o n
Add a project the name of W e l c o m e
Select the C + + P r o j e c t radio button
Click O K
Save the project to the \ as W e l c o m e . d e v see
Figure 25

November 2013 21 OUCS


DPFE C++

Figure 25

Dev-C++ creates a basic template source code file you


that you can build on. See Figure 26.

Figure 26

Physics/ITLP 22 November 2013


C++ DPFE

5.3. Creating your first program in eclipse


Creating a new project

Exercise 2 Creating a first program in eclipse


 Open eclipse
 Add a first program

Task 2 Step 1
To create a new project,
select File=> new =>
"C++ project"

Figure 27

November 2013 23 OUCS


DPFE C++

Task 3
Create a new empty Step 1
project Select an empty project using the “Mac OSX GCC"
toolchain on the Mac or the “Linux GCC toolchain”
on Linux

Step 2
Give the project the name H e l l o and accept the
default options

Figure 28

Physics/ITLP 24 November 2013


C++ DPFE

Task 4 To add a new source, or cpp file to the project, select


Add a new source file New  Source File as in Error: Reference source not
into the project found. Later you will be asked to add or copy header
Call the new source file files into the project. To do this select new  Header
“HelloWorld.cpp” File.

Figure 29
Task 5
Create an initial program Copy the following text into your new source file:
to pring “Hello World” to
the console. #include <cstdlib>
#include <iostream>

using namespace std;


int main (int argc, char* argv[])
{
std::cout << “Hello World” <<std::endl;
return EXIT_SUCCESS;
}

November 2013 25 OUCS


DPFE C++

Task 6 After editing projects, they should be built and


Build and run the project run. Initially, select build project from the project
menu.

Figure 30

Task 7
To run the project, and
for each subsequent
build + run cycle, just See Error: Reference source not found in Error: Reference
select the green play source not found
button.
See Error: Reference
source not found

5.4. What does this first C++ program do?


# include < c s t d l i b >
This statement is a pre-processor directive to include the contents of the header
file c s t d l i b in this program. This allows us to use functions for conversions of
numbers to text, text to numbers, memory allocation and many other utility
functions. You will be making use of these functions available in header file as
the course progresses.

Physics/ITLP 26 November 2013


C++ DPFE

#include <iostream>
Notifying the pre-processor to include in the program the contents of the header
file i o s t r e a m before compilation. This file must be included for any program
that outputs data to the screen or inputs data from the keyboard

using namespace std;


Using the namespace s t d tells the compiler to treat the names (m e m b e r s of the
namespace s t d ) in the s t a n d a r d l i b r a r y as though we had defined them in the
current program. The members we will be using throughout our programs are :
c i n - is the "standard input stream object" of the namespace std and we must
include the header file < i o s t r e a m > in order to use them (you will be using this
in the next exercise). The c i n object enables a program to input data from the
keyboard or other device.
c o u t - is the “standard output stream object” of the namespace std (you will be
using this in the next exercise). The c o u t object enables a program to output
data to the screen or other devices
e n d l - is a stream manipulator that writes a new line to output. e n d l stands for
e n d o f l i n e and is pronounced “endell”.
s t r i n g - allows us to use the s t r i n g c l a s s (more on classes later) as an
alternative to using C style character arrays.
"n a m e s p a c e s " are an advanced C++ feature. Dev-C++ adds the above
statement and for now we should accept this in the program.

Other parts of the program explained are:


int main(int argc, char *argv[]) -
m a i n ( ) is part of every C++ program. The parenthesis () after m a i n indicate
that m a i n is a program building block called a f u n c t i o n . Inside the function
parenthesis are arguments passed to the function. They are :

a r g c - is a count of the arguments supplied to the program of type int (integer).


* a r g v [ ] is an array of pointers to the strings which are the arguments.

In the programs we will be creating in this session we will not be using the
arguments a r g c and * a r g v [ ] and the statement i n t m a i n ( i n t a r g c , c h a r
* a r g v [ ] ) ; could be replaced with i n t m a i n () .

r e t u r n E X I T _ S U C C E S S ; tells the OS the program completed successfully. An


alternative way of writing this statement is: r e t u r n 0 ;

November 2013 27 OUCS


DPFE C++

Exercise 3 Modify the program


 Prompt the user to enter a number
 Read in the number
 Output the number to screen

Task 1 Step 1
Modify the program Add the following statements immediately above the
statement r e t u r n E X I T _ S U C C E S S ;
int anum = 0;

cout <<"Enter a number ";

cin >>anum;

cout <<"The number you entered is : " <<


anum << endl;

Step 1
Save the file as m a i n . c p p

The statement int anum = 0; defines a variable (a memory location) called


a n u m to store a number of type i n t to hold an i n t e g e r (i.e. 1, 4, 27). The
memory location is initialised with a value of 0 . It is good practice to initialise
variables at the same time you define them.
cout <<"Enter a number "; c o u t is a name that belongs to the
"n a m e s p a c e " s t d . The < < is the "s t r e a m i n s e r t i o n o p e r a t o r ". When the
program executes, the value to the right of the operator (“Enter a number”) is
inserted in the output stream and output to screen.
cin >> anum; c i n is the "i n p u t s t r e a m o b j e c t " of the "n a m e s p a c e " s t d . >>
is the "s t r e a m e x t r a c t i o n o p e r a t o r " used to get the character from the
keyboard.
cout <<"The number you entered is : " << anum << endl; This
statement concatenates the output by using multiple stream insertion operators.
<< endl is the stream manipulator that adds a new line.

Physics/ITLP 28 November 2013


C++ DPFE

Task 3 Step 1
Compile the program Build the project
If you have any errors in the code the line containing
the error will be highlighted. Correct any errors and
compile the program again. Repeat as necessary.

Task 4 Step 1
Run the program Run the project and select the box in Eclipse labelled
“C o n s o l e ” as in Figure 31.
Enter a number at the prompt and press E n t e r

Figure 31

The output is shown in Figure 32.

Figure 32

November 2013 29 OUCS


DPFE C++

5.5. Arithmetic Operators

Most computer programs perform arithmetic calculations. Table 1 summarises


the C++ arithmetic operators. When working with integer division where both
the numerator and denominator are integer the expression 15 / 6 evaluates to 2.
To get the remainder after integer division you would use the modulus operator
% . Note: the modulus operator can only be used with integer operands.
To establish the complete result of the following integer division, 15/6 requires
two operations.
15 / 6 = 2
15 % 6 = 3
The result being 2 remainder 3.

C++ C++ arithmetic Algebraic C++ expression


Operation operator expression

Addition + y+6 y+6


Subtraction - a-b a-b
Multiplication * c * d or cd c*d
Division / x x/y
x/y or y or x  y
Modulus % p mod q p%q
Table 1

5.5.1 Other fundamental data types:

Table 2 shows how you would declare and initialise four other data types for use
in programs.

Data type Example


Double double aDouble = 123.456;
Float float aFloat = 12.34;
Char char aChar = 'A';
Bool bool aBoolean = true;

Table 2

5.6. Characters

Characters are normally stored in variables of type char, but can also be stored
as i n t e g e r data types. Characters are represented as single byte integers in the
computer so it is possible to output a character as an integer or as a character.

Physics/ITLP 30 November 2013


C++ DPFE

All characters have a numerical representation in the computer and the ASCII
(American Standard Code for Information Interchange) character set shows each
character and its decimal equivalent. See appendix Error: Reference source not
found.

Characters can be read in with the following statements:


char aChar; declares a variable (a C h a r ) of type char.
cin >> aChar; this statement is used to read a character into the variable
aChar.

Note: After entering a character the <ENTER>key must be pressed before the
number is read by the program. To ensure the <ENTER> key press is ignored in
the program add the statement:
cin.ignore(); cin.ignore() is a function that reads and discards a character, in
this case the <ENTER> key press.

The following four statements correctly declare a variable of type char, output a
user prompt, then read a character and store it in the variable aChar. The enter
key press is then ignored.
char aChar;
cout << "Enter the CHARACTER A: " ;
cin >> aChar;
cin.ignore();

Characters can also be read into a program and stored as integers. The statement
bInt = cin.get(); uses the cin.get() function to read one character from the
keyboard and store it in integer variable bInt. The integer variable can then be
cast to a character, see section 5.8 C a s t s .

5.7. Strings

Next to numbers, strings are the most commonly used data type in
programming.
A string is a sequence of characters such as “O x f o r d ” or “S t . A n d r e w s ”. In C++
strings are enclosed in quotes. The quotes are not part of the string, they identify
the data type as a string.

Strings can be declared and initialised in this way:


string name = “Oxford”;
string firstName = “Ann”;

November 2013 31 OUCS


DPFE C++

To use the string type in your programs add the header file #include <string>
at the top of your program. This allows the use of part of the C++ library of
classes, the string class and its member functions.

The four statements below allow you to declare a string, read the string in and
output to the screen

string name;
cout << "Enter your name ";
cin >> name;
cout <<"You say your name is: " <<name <<endl;

Note: When reading in a string with a space such as “Ann Black” only the first
name is read into n a m e . You could create a second string and get the user to
enter B l a c k but this is inconvenient. To handle this situation use the
getline(cin, name); command instead of cin >> name;. This reads all key
strokes into n a m e until the <ENTER> key is pressed. The g e t l i n e function (more
on functions later) creates a string containing all of the characters from the input.

The string class has many useful functions you can use to manipulate strings. An
example is the length() member function.

string myName = "Sebastion";


cout <<"The length of the string myName is "<< myName.length()
<<endl;
This statement will output: - T h e l e n g t h o f t h e s t r i n g m y N a m e i s 9 .

See Appendix 24.16 for more information on the string class and member
functions.

5.8. Casts

On occasions in your programs you may want to store a value in a variable of a


different type. When there is a danger of a loss of information the compiler will
issue a warning. If you try to store a double as an integer you can lose
information in two ways.
 the fractional part may be lost
 the magnitude of the number being stored is too big
It is not possible to store 34.78 *1030 as an integer because the number is larger
than can be represented as an integer. However, you can store 123.0 as an
integer.

Physics/ITLP 32 November 2013


C++ DPFE

When you need to represent a value as a different type you can use the
s t a t i c _ c a s t notation as shown here:

To change a double to an integer:

int anInt;
anInt = static_cast<int>(doubResult); where d o u b R e s u l t is a double.

Legacy code may use the following notation to cast different data types:

anInt = (int) (doubResult);

To change an integer to a character:

char aChar;
aChar = static_cast<char>(bInt); Where b I n t is an integer.

November 2013 33 OUCS


DPFE C++

Exercise 4 Create additional projects


 Examine how comments can be added to a program
 Examine the use of strings and fundamental data types
 using different data types
 using the cast operator
 using string class
Task 1 Step 1
In eclipse, open the Examine the program C h a r N u m S t r i n g . c p p
project CharNumStri
n g and examine the The text at the top of the page starts with a (/*) and
program. Note how the ends with (*/).
string class has been /*This program ……… data types.*/.
used together with its
member function This is a block comment and is ignored when the
length(). program is compiled. The comment is over several
lines and gives the reader information on how the
program works.
Another way to write a comment on o n e line is by
putting two forward slashes in front of the text:
//this comment is on one line

Comments written this way must be on one line only.


All comments are ignored when the program is
compiled.
Examine the program and read all the comments. The
comments explain step by step how the program
works. It is good practice to comment your program.
Further exercises can be completed by copying parts
of this code and adding additional functionality as
required.
Task 2
Create another project,
call it E v e n . Write a
program that will read in
two numbers of type
d o u b l e and two
numbers of type
i n t e g e r . The program
should output the sum,
the product and the
difference of the d o u b l e
numbers. Also output
the quotient and the
fractional part of the
division of the two
integers.

Physics/ITLP 34 November 2013


C++ DPFE

Task 3
Modify your program in
T a s k 2 to read in two
characters. Enter the
characters “a ” and “Z ”.
Output the two
characters with the
character case changed.
i.e. “a ” becomes “A ” and
“Z ” becomes “z ”.
You will need to look at
the Appendix 24 to
establish the A S C I I
integer values of each
character.
Task 4
Create another project
called A d d r e s s .
Write a program that can
be used to collect user
data.
Output this data to
screen as shown in
Figure 33.

Figure 33

Task 5
Create another project
call it C a l c A r e a .
Write a program to
calculate the area of a
circle for different
radius.
Extend the program to
calculate the
circumference.
Extend it again to read
in the height of a
cylinder and calculate its
volume.
∏ = 3.141592
a = ∏r2, c= 2∏r, v=
ah

November 2013 35 OUCS


DPFE C++

Task 6
Create another project
call it CtoF.
The program will
prompt the user to enter
a temperature in
centigrade. The
program will calculate
the equivalent
temperature in
Fahrenheit and output
this to screen. The
formula is Fahrenheit
= 1.8 * Celsius +
32;

Task 7
Create a new project, call
it S e a r c h S t r i n g .
The program will display
a string of text to the
user.
The user will then be
prompted to select a
word from the sentence
then input a replacement
word. See section 24.16.
Figure 34
The string before and
after the update should
be displayed as in
Figure 34.

Physics/ITLP 36 November 2013


C++ DPFE

6 Introduction to Functions
Functions are used to encapsulate a set of operations and return information to
the main program or calling routine. E n c a p s u l a t i o n is data, information or
detail hiding.
Once a function is written, the detail of how it works is not important. It is only
necessary to understand what data input the function needs (its parameters) and
what output is produced.
The use of functions provides several benefits. It makes programs significantly
easier to understand and maintain. The main program function can consist of a
series of function calls rather than hundreds of lines of code. A second benefit is
that well written functions can be reused in multiple programs.
A function is d e c l a r e d with a p r o t o t y p e early in the program. A function
prototype consists of the r e t u r n t y p e , a f u n c t i o n n a m e and a p a r a m e t e r l i s t
indicating the data the function will receive. The function prototype is also called
the function d e c l a r a t i o n .
The function d e f i n i t i o n consists of the prototype and a function body, which is a
block of code enclosed in parenthesis.
Using a p r o t o t y p e is a way of telling the compiler the data types of any return
value and of any parameters being passed, to enable error checking to be done.
The d e f i n i t i o n creates the actual function in memory.
Arguments can be passed to functions in two ways. P a s s - b y - v a l u e is where a
copy of the argument value in the main program is made and then passed to the
function. The copy in the function only exists in memory as long as the function
is active. When the code within function has been run the memory is released
and the value held there lost. Changes to the copy of the variable in the function
do not affect the original variables value.
Arguments can also be p a s s e d - b y - r e f e r e n c e . When arguments are passed in
this way any changes made to the arguments in the function are reflected by
corresponding changes to that data variable in the calling part of the program.
Pass-by-reference is good for performance reasons because it can eliminate the
pass-by-value overhead of copying large amounts of data. In later sections we
will examine how p o i n t e r s can be used to p a s s - b y - r e f e r e n c e .

6.1. Creating a function


The format of a function prototype is:
return_data_type AnyFunctionName (argument_list)
The statement void FtoCent(int temp); has no return data type (v o i d ), it’s
name is F t o C e n t and it accepts an argument called t e m p of type i n t (integer).
It is not strictly necessary to give the argument a name ( t e m p ) in the prototype.
However, the argument t y p e must be specified. The statement void
FtoCent(int); is an alternative prototype and will compile satisfactorily.
The following exercise is an introduction to functions. You will learn a lot more
about functions in later exercises.

November 2013 37 OUCS


DPFE C++

Exercise 5 Examining a function


 In eclipse, open the project CharNumStringFunc
 Examine the structure of the program with a function prototype above
main() and the function definitions beneath main()
 Identify the static keyword

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project
Run the program entering the data as requested. The
CharNumStringFunc
output should be the same as Figure 35.

Figure 35
Step 2
Examine the following statements. Only the
important parts of the program are explained, the rest
has been covered in previous exercises.
All functions must be declared prior to use and there
are four p r o t o t y p e s in this program. Creating
prototypes allows the compiler to perform t y p e
checking on the arguments to ensure the input data is
the correct type before processing it.

void readChar(); function prototype. The function


is passed no value and returns no value. Note the use
of v o i d .

void passReadChar(int); function prototype. This


function receives an argument of type i n t (integer)
and returns no values.

Physics/ITLP 38 November 2013


C++ DPFE

int passStringRetInt(); function prototype. This


function returns an integer, int. No values are
received by the function ().

void readDouble(); function prototype. No values


are passed to the function and it returns no value
(v o i d ).

Calling functions:
readChar(); This is a function call to the
r e a d C h a r ( ) function. Notice no parameters are
passed. The function must therefore contain the code
to read in and output the user input.

passReadChar(aInt); This statement calls the


function p a s s R e a d C h a r ( ) and passes a character
into the function. The character argument is passed
as an integer.

cout <<passStringRetInt()<<endl<<endl;

In this statement passStringRetInt() is a function


call and the integer returned from this call represents
the number of characters there are in the name input
from within the function.
Look at the prototype for this function. You can see
the function returns an integer. When this statement
is output the function name is effectively replaced by
the return value, the number of characters in the
name input.

readDouble(); This function call does not pass a


value to the function and nothing is returned. The
function reads a value and outputs the square of the
value read in. Note how this function is called three
times but the code is contained within a function and
written once.

Function Definitions:
void readChar() { }
This is the function definition for readChar(). The
code within the braces is used to read in a character
and output the value to screen.

November 2013 39 OUCS


DPFE C++

void passReadChar(int number)


{ }
In this function an integer is passed to the function.
As characters are represented as single byte integers it
is possible to change the integer read in to a char.

int passStringRetInt()
{ }
The user enters a string in the function. The number
of characters in the string is established using string
class member function l e n g t h ( ) . This is returned to
the calling statement.

void readDouble()
{
static int aNum = 1;
aNum +=1;
}
N o t e here the use of the keyword s t a t i c . This has
defined the memory location a N u m as static and this
cannot change.
Memory is normally allocated to function variables as
the functions are called. When the function call is
complete the memory allocated is released and all
data in the function variables lost.
Using the keyword s t a t i c means memory is allocated
from a different part of memory and value in the
variable is maintained throughout the life of the
program.
The statement aNum +=1; increments the static
variable by 1 each time the function is called using the
assignment operator + = . In this example 1 is being
a d d e d to the variable a N u m .

Task 2
Remove the key word
s t a t i c from the
declaration static i n t
aNum = 1;
this is in the v o i d
r e a d D o u b l e ( ) function.
Compile and run the
program and see how the
program responds.

Physics/ITLP 40 November 2013


C++ DPFE

Exercise 6 Writing functions


 Open the project Even you created in Section 4, Exercise 4
 Create two functions
 Move calculations to functions
 Return a value from the function

Task 1 Step 1
Open the project E v e n Read two integers in to m a i n ( ) and pass them to a
you created in Section 4, function. The prototype is void intCalcs(int,
Exercise 4 and change int);
the structure of the i n t C a l c s ( ) function should calculate and display the
program to make use of result of the division and modulus of the two variables
functions. passed, see Figure 36.
Read in two doubles to variables in m a i n ( ) . Pass the
two doubles and the value of one integer to the second
function, the prototype is i n t C a l c s ( d o u b l e ,
double, int);
Within function C a l c s ( ) write statements to produce
the output as shown in Figure 36.
Most of the code already exists within m a i n ( ) .
Return the result of the multiplication of one double
and an integer, cast this value as an integer.
Display the returned value within m a i n ( ) , as shown
in the second last line in Figure 36.

Figure 36

November 2013 41 OUCS


DPFE C++

Task 2
Create a separate
function to change the
character case of two
characters. The
characters should be
passed from m a i n ( ) to
the function and the
results of the changes
displayed from within
the function.

Task 3
Create a new project, call
it C h u r c h H e i g h t .
Write a program that
will calculate the height
of a building given the
following information.
You are 2 7 0 metres
away from a church. The
angle from your feet to
the top of the church is
1 6 degrees, see Figure
37 and Figure 38.
The height of the Figure 37
building can be
calculated using the
formula:
tan(angle) = length
of opposite side/
length of the
adjacent side.
radians =
degrees*∏/180.
The program should
contain at least two
functions to calculate the
height of the building.
You will need to convert Figure 38
the angle to radians
before using the c m a t h
function t a n ( x ) . See
Appendix 24.15 for more
information on c m a t h
functions.

Remember to include
the header file < c m a t h >
in your program.

Physics/ITLP 42 November 2013


C++ DPFE

Task 4
Create a new project, call
it M e t r e s .
Write a function named
F I t o M e t e r s which takes
two double parameters,
a number of feet and a
number of inches and
returns a double number
of equivalent meters.
Assume there are 2.54
centimeters (0.0254
meters) in one inch.

Task 5
Create a new project, call
it S e c o n d s .
Two identical
experiments have been
conducted and the time
difference between the
two (in seconds) is
critical.
Write a function
(H M S e c o n d s ) that will
be called repeatedly and
will take three integer
parameters. A number
of hours, number of
minutes, and number of
seconds.
The total in seconds will
be returned to main()
and used in further
calculations to analyse
experimental results.

November 2013 43 OUCS


DPFE C++

6.2. Functions and Pass by Reference

In the previous section when working with functions all arguments passed to the
functions were copies of variable values from m a i n ( ) . The arguments were
passed by their v a l u e .
Pass by Value is the default argument passing mechanism for C++. When a
function is passed an argument the function gets a copy of the value from the
calling function (m a i n ( ) in previous examples). This copy value remains in scope
(see section 24.10) and available until the function call has completed when the
copy in the function is destroyed.
Therefore a function that takes v a l u e -arguments cannot change the variable
passed from m a i n ( ) because any changes only apply to local copies in the
function, not the actual caller's variables.
Passing variables to functions by r e f e r e n c e is very useful when we need to
change or update variable(s) via a function.
Pass by reference involves passing an address and not a copy of the data to the
function. This is usually more efficient than passing by value because there is no
requirement to copy large parts of memory.
However, this argument passing mechanism enables a function to modify any
function arguments even if it's not supposed to. To avoid this, declare all read-
only parameters as c o n s t and pass them by reference.
The format of a function prototype when using call by reference is:
r e t u r n - d a t a - t y p e f u n c t i o n - n a m e ( r e f e r e n c e p a r a m e t e r ) . To indicate a
reference parameter, an ampersand (& ) is written in the function prototype and
header after the parameter t y p e name
The statement void squared(int &); has no return data type (v o i d ), it’s name
is s q u a r e d and it accepts a r e f e r e n c e p a r a m e t e r (& ) of type i n t (integer).

The function definition would be:


squared(int & inVal)
{
inVal = inVal * inVal;
}

The function call would be:


squared(aValue); where a V a l u e is a reference to an integer value stored in
the memory location defined as a V a l u e . The address in memory of a V a l u e
is passed to the function s q u a r e d , not the value.

Physics/ITLP 44 November 2013


C++ DPFE

Exercise 7 Pass arguments by reference


 Examine how parameters can be passed by reference
 Create functions using parameters passed by reference

Task 1 Step 1
In eclipse, open the Compile and run the program. The output should be
project FunctionRef the same as shown in Figure 39.

Figure 39
Examine the function prototype:
void squared(int &);
This shows the function s q u a r e d accepts a
r e f e r e n c e p a r a m e t e r of type i n t . The reference
parameter is the memory a d d r e s s of the argument
passed to the function.
The function uses this address to both get and set the
value stored in variable a , (2 1 ) in m a i n ( ) . A
reference to this address is passed to the function with
the function call s q u a r e d ( a ) ;

Step 1
Examine the function v o i d s q u a r e d ( i n t & x )
x refers to the a d d r e s s of (a ) in main, that holds the
number 2 1 .
When parameters are marked as reference
parameters, the memory address of each argument is
passed to the function. The function will use these
addresses to both get and set values. The values
changed are the variables stored where the function is
called, m a i n ( ) in this example.

November 2013 45 OUCS


DPFE C++

Task 3
Create another project
call it F u n c R e f M a r k s .
Read in the name of a
student and three exam
marks.
The marking has been
too severe in the three
exams and all students
are to receive an
additional 5 marks.
The student name has
been entered incorrectly
and needs to be changed.
Prompt the user to enter
the change in student Figure 40
name and value that
each result will be
increased by.
Making just one function
call modify the exam
results and the student
name.
All the variables should
be stored in the m a i n ( )
function. The output
should be similar to that
shown in Figure 40.
Task 4
Open the file
F u n c C o n s t R e f and
examine the program.
Compile the program
sorting any errors.
Arguments are being
passed by reference but
incorrectly, sort these
errors. There are also
some problems with the
program logic.
When the program is
compiled and run the Figure 41
output should be as
shown in Figure 41.

Physics/ITLP 46 November 2013


C++ DPFE

7 Classes and Objects

In the previous section we have been working with simple programs that display
messages to the user, store data input as different data types, manipulate the data
in some way and output the results to screen.
We now look at objects and classes. In the real world there are objects
everywhere, students, staff, cars, birds, houses and many more. All objects have
a t t r i b u t e s , these are similar to the variables created in previous tasks. Some
attributes of a student may be height, weight, race, course of study etc. All objects
exhibit b e h a v i o u r s or operations, cars accelerate and decelerate, students
matriculate, enrol on courses and leave university.
Now, what is the relationship between a class and an object? A good analogy
would be, from a drawing for a house it would be possible to build many houses,
and from a class it would be possible to build many objects.
If we had a student class we could create many objects from the student class to
represent the many students enrolling. Each of these objects would be uniquely
identified. They would share common attributes and exhibit common
behaviours. If we wanted an object to perform some task we would call the
appropriate member function allowing an operation to take place changing the
behaviour of that object.
Member functions are different from the functions you have created so far.
Member functions are always associated with objects and are called or invoked
with a dot notation, o b j e c t . m e m b e r f u n c t i o n n a m e ( ) . An example is
s t u d e n t 1 . g e t N a m e ( ) . The object is s t u d e n t 1 and the member function is
getName().
Member functions contain the detail of how the technical aspects of some
operation will be processed. When member functions are invoked these technical
issues are hidden from the end user. When the member function is asked to do
some operation a message is sent (a member-function call) telling the member
function of that object to perform the operation detailed in the function.
Functions are not completely new, we have had a brief introduction and you have
already created some of your own. Note also that m a i n ( ) is a function and is
called automatically when you run your programs. However, it is not a member
function as there is no object associated with it.

November 2013 47 OUCS


DPFE C++

7.1. Creating your first class

Exercise 8 Creating a class


 Create a class
 Create an object of the class

Task 1
Create a new project, call
it S t u d e n t . Name the
new source file
StudentUG.cpp.
From the directory
where you unpacked the
source materials, open
the file called
S t u d e n t U G . t x t . Copy
the C++ program.
Replace the default C++
template file
(S t u d e n t U G . c p p ) with
the file copied from Figure 42
StudentUG.txt.
The program should look
like Figure 42.
Compile and run the
program.

Before you can create the object m y N a m e it is necessary to define the class from
which the object will be created. The class definition is shown below.

class StudentUG { /*start of class definition*/

public: /*public is access specifier, it means the


function displayName()
(a member function) is open to the public. It
can be called by other functions in the class and
functions of other classes*/

void displayName() /*start of member function */


{
cout <<"My name is Larry Martin" <<endl;
} /*end of member function */

Physics/ITLP 48 November 2013


C++ DPFE

}; /*end of class definition. */


/*N o t e : a semicolon is required at the end of the class definition*/
Within m a i n ( ) the statement StudentUG myName; creates the object m y N a m e
of class S t u d e n t U G .

The statement myName.displayName(); is used to call the member function


d i s p l a y N a m e ( ) of object m y N a m e .

As we have seen previously the function m a i n ( ) is called automatically when our


programs are executed. However, member functions (d i s p l a y n a m e ( ) is one, we
could have many) must be called in this way, o b j e c t N a m e . f u n c t i o n N a m e ( ) .

The member function d i s p l a y N a m e ( ) is preceded by the word void. All


functions can return values, this one does not. The word void preceding the
function name indicates nothing is being returned. If this function returned an
integer the definition would be i n t d i s p l a y N a m e ( ) .

When you use functions it is common to pass data (called parameters) to the
function. The function then manipulates the data before displaying an output
and/or returning a value.

To pass a parameter to the function in the s t u d e n t U G class the calling statement


in m a i n ( ) would be:
myName.displayName(name); where n a m e is a string (a series of characters)
that contains a value read in from the keyboard.

In order for the function d i s p l a y N a m e ( ) to recognise the parameter being


passed the function declaration is changed to include the parameter (n a m e ) and
type (s t r i n g ) as shown in Figure 43.

Figure 43

The statement cout <<"Hello " << name << endl; provides the output.

November 2013 49 OUCS


DPFE C++

7.2. Member functions and Passing parameters

Exercise 9 Passing parameters


 Function calls with parameters

Task 1
Modify the program you
created in the previous
exercise S t u d e n t U G . c p p
to read in a student name.
The name should be passed
to a member function. The
parameter should be output
from within the function to
welcome the user to C++ Figure 44
programming. The output
should be similar to Figure
44.
Task 2
Modify the program in the
above task to read in two
more names. Each name
will be for a different
student and you will need
to create additional
o b j e c t s (instances) of the
class.

7.3. Data Members


In all the programs written so far, the variables have been declared inside the
m a i n ( ) function. Variables declared inside a function are local to that function
and cannot be accessed from outside that function.
You have created a student class and it would be reasonable to assume that a
student would be following a particular course. So c o u r s e N a m e might be one of
several attributes of a S t u d e n t object. Attributes are represented as variables in
a c l a s s d e f i n i t i o n . These variables are called d a t a m e m b e r s and must be
declared inside the class definition. When you create an object of a S t u d e n t
class each object has a unique memory location for its data members.
Figure 45 shows data member s t u d N a m e declared in the class definition. The
access specifier p r i v a t e means that only member functions of the class in which
the attribute was declared can use this data member.

Physics/ITLP 50 November 2013


C++ DPFE

Figure 45

When data members are declared as p r i v a t e the data is hidden. This is called
e n c a p s u l a t i o n and means the attributes of the object are hidden and can only
be accessed via member functions.
As there is no direct way to change a data member you will also need to create a
m e m b e r f u n c t i o n to set the data member to a value and create a second
m e m b e r f u n c t i o n to output the value held there.
Data members can also be declared p u b l i c . A data member that is declared
p u b l i c can be accessed from any (non-member) function.
A p r o t e c t e d data member can only be accessed by member functions of its own
class and by member functions of classes derived from this class. We will learn
more about derived classes and inheritance later.

Exercise 10 Using data members


 Setting a data member
 Getting a data member

Task 1
Create a new project, call it
S t u d e n t G e t S e t . Create a
new source file call it
StudentCourse.cpp.
From the directory
where you unpacked
the source materials,
open the file called Get
Set.txt.
Copy the C++ program.
Figure 46
Replace the default C++
template file
(S t u d e n t C o u r s e . c p p )
with the file copied from
GetSet.txt.
Compile and run the
program, it should look like
Figure 46. You may have to
sort some compilation
errors.

November 2013 51 OUCS


DPFE C++

Task 2
Examine the member
function r e t u r n N a m e ( )
shown in Figure 47. This
function produces the
output but what does
g e t N a m e ( ) do?

Figure 47

Task 3
Modify the
S t u d e n t C o u r s e source
file to enable the user to
add a student name,
enrolment date and
number of years of course.
Once entered this data
should be output to screen.
Figure 48
You will need to create
additional d a t a m e m b e r s
and m e m b e r f u n c t i o n s to
achieve this.
The output should be
similar to Figure 48.

Exercise 11 More Objects


 Creating a second object
Task 1
So far you have created one
S t u d e n t C o u r s e object. It
is about time we had a
second student on the
course. Create a second
object of the class
S t u d e n t C o u r s e . You will
need to add the second Figure 49
statement shown in Figure
49 to add the new object
y o u r N a m e . Call the
member functions passing
parameters as necessary.

Physics/ITLP 52 November 2013


C++ DPFE

7.4. Constructors
When you create objects from the S t u d e n t C o u r s e class it is necessary to give
initial values to all the data members. If we were entering data for five people
and they were all following the same course of study it would make sense to
initialise the c o u r s e N a m e data member (it is possible to initialise some or all of
the data members) when each object is created.
A c o n s t r u c t o r is a special kind of function that must have the same name as the
class. Constructors are normally defined as p u b l i c and never have a return type.
They can be used to automatically initialise data members.
In previous programs you have written, a d e f a u l t c o n s t r u c t o r has been
provided by the compiler. However, it is not possible to pass parameters to a
default constructor function, so the data members in the programs created so far
have not been automatically initialised. To initialise these data members you
created member functions that assigned values to data members.
Although a default constructor is provided at compilation time it is a good idea to
create your own so that the data members can be initialised.
It is worth noting here that functions (constructors are functions) can be
o v e r l o a d e d . This means it is possible to have more than one function with the
same name. Note that overloaded functions (functions with the same name)
must have different types of, or number of arguments.
Constructors (functions) can also be overloaded with more than one function
with the same name but different types or number of parameters. Fortunately for
us the compiler automatically calls the correct function whose parameters match
the arguments used in the function call. There is more information on function
overloading in section 10.5.

November 2013 53 OUCS


DPFE C++

Exercise 12 Using constructors


 Create a new file using constructors
 Add a third constructor

Task 1
Create a new project, call it
C o n s t r u c t o r . Create a
new source file call it
Constructor.cpp.
From the directory
where you unpacked
the source materials,
open the file called con
structor.txt.
Copy the C++ program.
Figure 50
Replace the default C++
template file
C o n s t r u c t o r . c p p with the
file copied from
constructor.txt.
Compile and run the
program, it should look like
Figure 50. You may have to
sort some compilation
errors.
Task 2
In the constructor shown in
Figure 51 what does the
statement
setCourseName(name);
do?

Figure 51

Task 3
Create a third constructor
that will take arguments of
y e a r s and e n r o l D a t e .
Add a third object, call it
student3.
Write a statement that will
output the results of a call
to this additional
constructor.

Physics/ITLP 54 November 2013


C++ DPFE

Task 4
Each student has an I D
n u m b e r and a
supervisor.
Modify the program to
allow student I D ’ s and the
n a m e s of supervisors to be
added to each object
created.
Create member functions to
allow the user to add or
modify both the I D and
supervisor names.
Create member functions to
output these details to
screen.

7.5. Destructors
Both constructors and destructors are special class methods. We have seen how a
constructor is called whenever an object is defined.
A destructor is a method that has the class name prefixed by a tilde, ~ .
Destructors cannot return values and therefore have no return type specified.
Unlike constructors, destructors have no arguments and thus cannot be
overloaded. Overloading a function is using the same name for more than one
function provided the functions have different parameter, see section 10.5.
An object's destructor is called whenever an object goes out of scope. The
purpose of the destructor is to clean up and free any dynamically allocated
memory that the object was using and release other system resources.
In the examples used so far no destructor has been provided for any class created.
In these programs it has been unnecessary. If we do not explicitly provide a
destructor the compiler will create an empty destructor in the same way that an
empty constructor is created if one is not explicitly created.
When classes are created, any objects instantiated from them that contain
dynamically allocated memory will need destructor methods (functions) added to
implicitly free any dynamically allocated memory when the object goes out of
scope.
In the class example shown below the destructor function is ~ Staff ().

class Staff {

private:
int staffid;
double staffsal;

public:

November 2013 55 OUCS


DPFE C++

Staff (int staffid = 0, double sal = 0.0); /*constructor*/


~ Staff() {}; /* destructor*/

int getID()
{return staffid;
}

void setID(int id)


{staffid = id;
}

double getSal()
{return staffsal;
}

void setSal(double sal)


{staffsal = sal;
}

}; /*end of class*/

Physics/ITLP 56 November 2013


C++ DPFE

7.6. Separate Class Files for Reusability


The programs you have created so far consist of one . c p p source code file that
contains a class definition and a m a i n ( ) function. C++ is an object-oriented
programming language and one of the aims is to create classes that are reusable.
It is not possible to reuse the source code from the programs you have created so
far. This is because each program contains a m a i n ( ) function. As things are, if
you include an existing class file in a new program you will also be including a
m a i n ( ) function. As there can only be one m a i n ( ) function, compiling this
program will cause compilation errors.
The way to reuse the class information in the source code file is to extract the
class information and put it in a header file that has an . h extension.
To get a new program to include the header file use the pre-processor directive
#include.

Exercise 13 Using header files


 Open an existing project
 Create a header file
 Use the pre-processor directive

Task 1 Step 1
Open an existing project. In eclipse, open the project Header
Create a header file and Add a new Source file to the project, F i l e | N e w |
include reference to this in Source File
the source code file. Save and name the file O x S t u d e n t s . h in the same
When m a i n ( ) is called the folder as H e a d e r .
class definition in the
header file is used to create
objects of the class defined
in the header file. Step 1
Cut the class definition code from H e a d e r . c p p file
and paste it into the O x S t u d e n t s . h file.
As you will be using input and output in the class
header file you need to include the iostream
library. Add # i n c l u d e < i o s t r e a m > , # i n c l u d e
< s t r i n g > and u s i n g n a m e s p a c e s t d ; to the top
of the header file.

Step 1
Compile the program
You should get a compilation error at line
OxStudents myName;
This is because m a i n ( ) does not know about the
header file containing the class information.

November 2013 57 OUCS


DPFE C++

Step 1
Add the statement # i n c l u d e " O x S t u d e n t s . h "
beneath the other # i n c l u d e directives in
H e a d e r . c p p file.
Compile and run the program
The statement # i n c l u d e " O x S t u d e n t s . h "
instructs the C++ pre-processor to replace the
directive with a copy of the contents of
O x S t u d e n t s . h before the program is compiled.
With the O x S t u d e n t s class in a header file it is
now possible to include and reuse that class in any
program by just adding the appropriate header file
to m a i n ( ) .
N o t e : Header files written like this can only be
included once in a project. We want to make the
code re-usable. We get around this in 15.5
N o t e : User defined header files can be kept in the
same directory as the source code files. It is
normal to separate them in larger projects. This
requires eclipse to be configured to look in a
different directory for include files. This is out of
scope.

Task 5
Create another project call
it C o u n t r y . Modify the
m a i n ( ) source code to use
the class in the header file
#include
"OxStudents.h".
N o t e : the O x s t u d e n t s . h
file will need to be copied to
Figure 52
the C o u n t r y project folder.
The user should enter a
name and a country which
should be output to screen,
see Figure 52. Modify the
source code in main and
OxStudents.h to achieve
this.

Physics/ITLP 58 November 2013


C++ DPFE

Task 6
Open the project
C o n s t r u c t o r you created
in Exercise 12.
Create a new header file
that includes the class
definition, save this as
constructor.h.
To use the class from within
main() add #include
"constructor.h" at the
top of the program where
the other header files are
included.
Test the program.

November 2013 59 OUCS


DPFE C++

Task 7
OPTIONAL

Create a new project, call it


Employees.
From the directory
where you unpacked
the source materials,
open the file called Em
ployees.txt
Replace the default file in
the project with Figure 53
Employees.txt.
Create a header file, call it
employee.h.
Add two constructors, one
default and another to
accept the parameters
being passed from m a i n ( ) .
Create member functions
to:
 set the salary
 modify the salary
 return the full name
 return the salary
Modify the main program
to call the member
functions.
The completed program
should provide an output
similar to Figure 53.

Physics/ITLP 60 November 2013


C++ DPFE

8 Basic Control Flow


The programs you have created so far are limited in they run through a sequence
of instructions once and then stop. Most computer programs will make decisions
and carry out different actions determined by the user input.
C++ has three kinds of control structures:

S e q u e n c e statement - the computer executes the statements one after


another. All the programs you have written so
far use sequence statements.
S e l e c t i o n statements - if, if…else, switch.
The i f selection statement selects an action if a
condition is true or skips the action if false.
The i f . . . e l s e selection statement selects an
action if a condition is true or performs a
different action if the condition is false.
The s w i t c h multiple selection statement can be
used to perform many different actions based on
a character or integer value.
R e p e t i t i o n statements - while, for, do…while.
The w h i l e and the f o r statements perform
actions within their bodies zero or more times
depending. If the loop condition test is initially
false no actions will occur.
The d o … w h i l e statement will perform the
actions in the body at least once.

8.1. Selection - if…else statement


The if selection structure is used to choose among alternative courses of action.
The structure of the statement is:
if (mark >= 50)
cout << "Passed";
else
cout << "Failed";

If the condition ( m a r k > = 5 0 ) is t r u e the statement following it is executed cout


<< "Passed";
If the condition is f a l s e the statement is ignored and control is passed to the e l s e
part of the selection, and statement following e l s e is then executed cout <<
"Failed";
i f … e l s e selection statements can also be nested within other i f … e l s e selection
statements.

November 2013 61 OUCS


DPFE C++

Exercise 14 if …else selection


 In eclipse, open the project “If”
 Examine how the if…else double selection statement works
 Modify the program

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
p r o j e c t I f . There is
one . c p p file and one . h Run the program. The output should be the same as
header file. Figure 54.

Figure 54

Step 1
Examine the v o i d g e t G r a d e s ( ) member function in
the S t u d e n t M a r k s I n t e r f a c e . h file.
The if single selection statement performs only one
action when the condition tested ( E x a m 1 > = 9 0 ) i s
true.
if(Exam1 >= 90)
cout<< "the Exam1 grade is 'A'" <<endl;

The i f selection statement returns t r u e only when


E x a m 1 is greater than or equal to 9 0 . The output is
" t h e E x a m 1 g r a d e i s ' A ' " . There is no mechanism
for testing for other scores with the single i f selection
statement and the program will continue with the next
statement in the program.

N o t e : > = is a r e l a t i o n a l o p e r a t o r (greater than or


equal to). For more information on r e l a t i o n a l
o p e r a t o r s see Appendix 24.4 Relational and Equality
Operators.

Physics/ITLP 62 November 2013


C++ DPFE

To test for, and provide actions for two distinct


conditions we can use the i f … e l s e selection
statement.
It is necessary to specify an action when a condition is
t r u e ( E x a m 1 > = 9 0 ) and an alternate action when
the condition is f a l s e .
if (Exam1 >= 90)
cout<< "the Exam1 grade is 'A'" <<endl;
else
cout<< "the Exam1 grade is 'B'" <<endl;

Although this is closer to meeting the requirements of


the program it still needs to be improved.
By having nested i f … e l s e statements and using
appropriate relational operators > = (see Figure 55) it
is possible to test for multiple test scores.

Figure 55
The appropriate grade is selected and user prompted
of the result from within g e t G r a d e s ( ) member
function.

Task 4
A second student has
just joined the class.
Modify your program so
the user is prompted to
add details for a second
student and their results
for the four exams.
Modify the code so the
user is prompted to add
a Course Name.
Output the results to Figure 56
screen. They should
look similar to Figure 56.

November 2013 63 OUCS


DPFE C++

8.2. Selection - switch multiple selection statement


The s w i t c h multiple selection statement can be used to perform many different
actions based only on a single integer value. Note however, the switch statement
can only be applied in narrow circumstances. The tests must be constants and be
integers. Let’s compare the two statements:

O K – Test is 1, a constant and an integer N O T O K – Test is not constant integer

Exercise 15 switch selection


 In eclipse, open the project IfSwitch
 Examine how the switch double selection statement works
 Modify the program

Task 1
In eclipse, open the Compile the program, sorting any compilation errors.
project IfSwitch. Run the program. The output should be the same as
There are two files, one Figure 57.
. c p p files and one . h
header file.

Figure 57

Physics/ITLP 64 November 2013


C++ DPFE

Task 2 Step 1
To see how the s w i t c h Examine the v o i d g e t G r a d e s ( ) member function in
statement gets its the S t u d e n t M a r k s I n t e r f a c e . h file, see Figure 58.
parameters and to
understand how
characters can be used in The use of the i f statement was explained in the last
a s w i t c h statement. exercise. The statement c o u n t G r a d e s ( ‘ A ’ ) is new.
It is calling the function c o u n t G r a d e s and passing a
character parameter ‘A ’ as the student achieved > =
90 marks.

Other grades assigned and passed to the function are


B (79-85), C (50-74) and F <=49.

Figure 58

November 2013 65 OUCS


DPFE C++

Step 1
Exam the code in c o u n t G r a d e s member function.
See Figure 59

Figure 59

A character parameter is passed to the function.


All characters typed at the keyboard have a numerical
representation in the computer and are stored as 1-
byte integers. It is therefore possible to treat a
character both as a character and as an integer.
As the character input at the keyboard can be
represented as an integer it meets the criteria for use
with the switch statement.
The switch statement consists of a series of c a s e
labels and a d e f a u l t case statement. In Figure 59
these are used to increment the different counters
(a C o u n t … f C o u n t ) depending on the value of
parameter passed. If there is no match between the
l e t t e r (the controlling expression) and the c a s e
labels the d e f a u l t case statement executes.

Physics/ITLP 66 November 2013


C++ DPFE

Task 4 Step 1
Exam how the count of Examine the member function o u t P u t G r a d e s ( )
grades is output. shown in Figure 60

Figure 60
This member function outputs the object member
variables a C o u n t . . . f C o u n t . The statement
s t u d e n t 1 . o u t P u t G r a d e s ( ) ; in m a i n ( ) is used to
call the member function and output the total of each
grade achieved by the object s t u d e n t 1 .

Task 5 Step 1
Create a new Write a program that reads a product ID (Product 1 -
project, call it Electr 4 ) and the q u a n t i t y required.
onicsOutlet.
A s w i t c h statement should be used to determine the
You sell the following product sold.
four products at the unit
price shown. Items that are sold in quantities > 9 9 units are
reduced in price by 10% before tax is applied.
Product 1:Astable
multivibrators The output should show the cost per item, the VAT
@£15.45 element and the total cost including VAT at 17.5% as
shown in Figure 61.
Product
2:Integrated-Circuit
Timers @ £21.78.
Product 3:ECL
@£15.78.
Product 4:BiCMOS
digital circuits
@£34.99.

Figure 61
N o t e : Use a class file (header file).
Create a default constructor to initialise all data
members.
Initialise the product ID, the Unit Cost and the
product name in the switch statement. To do this you
will need to overload the default constructor.

November 2013 67 OUCS


DPFE C++

8.3. Repetition – while, do…while and for loops


The while statement is commonly used to carry out repeated steps, perhaps
reading in values before doing a calculation on values read in. The format of the
code is
while (condition)
statement
This can be read as, w h i l e the condition is t r u e continue to do the s t a t e m e n t s
until the condition is f a l s e .

Exercise 16 while loop


 In eclipse, open the project While
 Examine how the while repetition statement works
 Modify the program

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
p r o j e c t W h i l e . There
is one . c p p file and one Run the program. The output should be the same as
. h header file.
Figure 62.

Figure 62

Physics/ITLP 68 November 2013


C++ DPFE

Open the w h i l e . h file and examine the member


function g e t S t u d e n t D e t a i l s ( ) .
The condition tested in this loop is the c o u n t e r value.
The statement w h i l e ( c o u n t e r < = 4 ) will only be
true while the counter is less than or equal to 4. All the
statements within the braces { } will be executed when
the condition is true.
In this example, to make the condition f a l s e and
terminate the loop, the counter value has to be
incremented (it could be decremented depending on
design).
The statement c o u n t e r + + ; achieves this,
incrementing counter by 1. For more detail on
incrementing variables see Appendix 24.3.
N o t e : It is easy to forget that the counter must be
incremented or decremented (depending on how you
designed the program). If you fail to change the
counter value you will create an infinite loop where
the statements inside the while loop will run forever.

Task 4
Modify the program in
the task above to read in
the results of tests for
two students. Each
student has taken 4
tests. Output the total,
average, highest and
lowest scores for each
student.
N o t e : you will need to
use a method of
selection to establish the
highest and lowest
marks inside the while
loop.

November 2013 69 OUCS


DPFE C++

Task 5
Create a new
project, call it BMI.
The program should
calculate the body mass
index (BMI) of a person
where their height is in
feet and inches and their
weight is in stones and
pounds.

1 foot =12 inches,


Figure 63 BMI Calculator
1 inch = 25.4 mm,
1 stone = 14 pounds,
1kg = 2.2 pounds.

BMI =
weight(kg)/height(m)2

Offer some medical


advice to the user using
these criteria:
BMI <25 = Good
25-29 = OK
>29 = Overweight

Figure 63 shows the


output from the BMI
calculator.

Physics/ITLP 70 November 2013


C++ DPFE

Task 6
OPTIONAL
Create a new
project, call it
avgTemp.

Seven temperature
readings are taken at
each of three locations in
Oxfordshire and stored.

Stored in class objects for


each location are the
details of the location:
The nearest town and a
six figure grid reference. Figure 64

Create a temperature
class to accept the
temperature readings
and other details for each
location.

Calculate the mean


temperature at each
location and output this
to screen. The output
should be similar to that
shown in Figure 64.

Task 7
OPTIONAL
Using the output shown
in Figure 65 write a
program that will output
this display.
Create a class file that
can be used to display
this detail. The program
does not have to be
functional other than to
display this screen and
verify the account and Figure 65
PIN numbers.

November 2013 71 OUCS


DPFE C++

Exercise 17 for loop


 Modify the program using the for loop

Task 1 The format of the f o r loop is:


Modify the program in for (i = start; i <= end; i++)
Exercise 14 Exercise
{
16Task 4 to use the f o r
loop. You will need to Statements;
modify the code in }
student.h.
In the above piece of code it is assumed i is declared
The code you need to as a variable in the declarations section within the
add is shown in Figure program.
66.
N o t e : The f o r loop is a
special kind of w h i l e
loop.

Figure 66
Figure 66 shows the code required to read in four
exam marks.
N o t e : The integer i used to control the loop and has
been declared within the brackets of the f o r loop (i n t
i = 0 ; ). This means that i only exists within the loop.
When the loop ends, i ceases to exist. This is called
the s c o p e of the identifier.
See appendix Scope 24.10 for more information.
Task 2
OPTIONAL
Create a new
project, call it Books
.
The program should
create three instances of
a class called B o o k s .
Create each of the
objects inside a f o r
loop.
Create member
functions to add a Title,
Author and date of
publication.
Output the details of the
three books to screen.

Physics/ITLP 72 November 2013


C++ DPFE

Exercise 18 do…while loop


 Understand the difference in while and do…while loops

Task 1 Step 1
Note: You should Open D o W h i l e project
complete the chapter on
Run the program entering the numbers 19, -19, 19, -19
classes before
when prompted
attempting this task.
The output of the program is shown in Figure 67.
In eclipse, open the
project DoWhile.
Establish how the do…
while loop can effect a
program written to
verify user input.

Figure 67
Establish why when using the d o … w h i l e loop for
repetition a negative value (-19 as shown in Figure 67)
is established as being greater than zero.
H i n t : Look at where in the block the condition is
tested.
Task 2
Note, you do not need
the classes chapter to
attempt this exercise.
Create a new
project, call it Factor
ial

Using different
repetition statements
write a program to
calculate and display the Figure 68
factorial of a value
entered by the user. See
Figure 68.
The factorial of '6' is
1*2*3*4*5*6 = 720.

November 2013 73 OUCS


DPFE C++

9 Arrays, vectors and lists


Arrays, vectors and lists are all types of data structures. Data structures are areas
of memory where collections of the same data type are held. The main difference
between arrays, vectors and lists is that arrays stay the same size throughout the
program execution whereas vectors and lists can grow automatically to any size.
Arrays consist of a series of elements (variables) all of the same type placed
consecutively in memory. Each of the elements can be individually referenced by
adding an index to a unique name.
The advantage of using arrays compared to using discrete variables (the way we
have stored values so far) is it is possible to store any number of values of the
same type in an array without having to declare many different variables each
with a different identifier.
With arrays it is possible to store 100 student exam marks, or 100 student names
with one unique identifier.

Vectors and lists are container classes, part of the Standard Template Library
(STL). This is a general-purpose C++ library of algorithms and data structures
that we can use in our programs. While some aspects of the library are very
complex, it can often be applied in a very straightforward way that allows reuse of
sophisticated data structures and algorithms.
As with an array, v e c t o r and l i s t can hold objects of various types. However,
unlike arrays, vectors and lists can resize, shrink and grow as elements are added
or removed.
The standard library provides access via iterators, or subscripting. Iterators are
classes that are abstractions of pointers (more on pointers later). They provide
access to container classes using pointer-like syntax and have other useful
methods as well.
The use of vectors, lists and iterators is preferred to arrays and pointers. By using
containers common problems involving accessing past the bounds of an array are
avoided. Additionally, the C++ standard library includes generic algorithms (an
algorithm is a set of instructions on how to perform a task) that can be applied to
vectors lists and other container classes.

9.1. Declaring and using arrays


Arrays are declared indicating the type and number of elements in the following
way:
type arrayName[arraySize]
Examples are:
int inNumbers[20]; an array called i n N u m b e r s of 20 i n t e g e r s .
char inName [20]; an array called i n N a m e of 20 c h a r a c t e r s .
float ExamMarks[5] = {0}; an array called E x a m M a r k s of 5 float with all
elements explicitly initialised to zero.

const int size = 5; declaring a constant variable s i z e .

Physics/ITLP 74 November 2013


C++ DPFE

float ExamMarks[size]; When the constant variable s i z e is applied to the


array declaration the number of elements is set to 5. This cannot be changed
during runtime of the program. However, it is handy when the number of array
elements needs to be changed. Changing the constant value s i z e changes the
number of elements wherever the E x a m M a r k s array is used in the program.
int numArray [2] [3] is a multidimensional array with 2 rows and 3 columns.

N o t e : Arrays have been used in C++ for many years and there will be code you
work with that was written before Vectors. Vectors are new in C++ and are
preferred to arrays and pointers. Common problems involving accessing past the
bounds of an array are avoided when using vectors.

Exercise 19 Creating an array to hold exam results


 Open project A r r a y
 Examine how values are written into the array
 Modify the program to read in 10 exam marks

Task 1
In eclipse, open the Compile the program, sorting any compilation errors.
project Array
Run the program adding five exam results. The
output should be similar to Figure 69.

Figure 69

November 2013 75 OUCS


DPFE C++

Step 1
Examine the following statements
d o u b l e E x a m M a r k s [ 5 ] = { 0 } ; This statement
declares the array, setting it’s size to 5 elements and
explicitly initialising all elements to zero.
c o u t < < " E n t e r E x a m M a r k " < < i + 1 < < " " ; This
statement prompts the user to enter an Exam mark
into the array at element i + 1 .
Using the notation i + 1 indicates to the user to enter
E x a m M a r k 1 not exam mark 0 which would be less
intuitive.
Array elements are numbered from 0 to n-1. So an
array that holds 2 0 i n t e g e r s will be addressed from
element 0 t o 1 9 .
ExamMarks[0]…ExamMarks[19]
The first number will be entered into element [ 0 ] .
The last into element [ 1 9 ] .
cin>>ExamMarks[i];
This statement reads in the user input and stores the
values in the array elements of E x a m M a r k s [ i ] . i is
incremented within the f o r loop and starts at 0 .
Task 2
Modify the program to
calculate the highest and
lowest numbers in the
array.

Physics/ITLP 76 November 2013


C++ DPFE

Task 3
Create another project
call it N a m e s . The
program should read in
student names, these
will be held in an array.
The user should enter
three names. The names
should be output to
screen, see Figure 70.
Although not part of the
STL, the string class is
part of the ANSI C++
standard library and has
many useful member
functions. (See
Appendix 24.16, String
class). Figure 70

One member function is


l e n g t h ( ) . This is used
in Figure 70 to establish
the number of characters
in each name entered.
Modify your program to
calculate the number of
characters in each name
entered and display the
results.

Task 4
OPTIONAL
Create another project
call it A r r a y N a m e A g e .
The program should
read in two patient
names with their age.
The user should be
prompted to add the age
after the name has been
added.
The output should be as Figure 71
shown in Figure 71.
Modify the program to
establish the average
age. Output the result.

November 2013 77 OUCS


DPFE C++

9.2. Searching Arrays with Linear Search


Linear search allows the user to search the array and establish whether the array
contains a value that matches a search criteria defined by the user.
The search compares each element of the array with the user input. The array is
not sorted and this method of searching works well for small arrays. For large
arrays linear searching is inefficient and it is necessary to use other forms of array
searching after the array has been sorted.

Exercise 20 Linear Search


 In eclipse, open the project LinearSearch
 Examine how random values are written into the array
 Modify the program to read in 10 exam marks

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project LinearSearc
h Run the program; choose a number between 1 and
1 0 0 . The output should be similar to Figure 76.

Figure 72

Physics/ITLP 78 November 2013


C++ DPFE

Step 2
Examine the following statements
m y A r r a y [ i ] = ( 1 + r a n d ( ) % 1 0 0 ) ; This statement
uses the r a n d function, part of the < c s t d l i b > header
file. r a n d ( ) % 1 0 0 produces integers in the range 0 to
99.
The function l i n e a r S e a r c h takes three arguments.
The array name, the size of the array, the third
argument is the search value.
if ( array[j] = = value )
return j;
This selection statement compares each element to
the search value. If the search value is in the array the
element number is returned to m a i n ( ) otherwise -1 is
returned.
The i f selection statement i f ( e l e m e n t ! = - 1 ) in
m a i n ( ) is used select the output indicating a
successful or unsuccessful search.

Task 2 Step 1
Create another program Create a project, call it S e a r c h C o u n t V a l
to output a count of the
Create a new source file S e a r c h C o u n t V a l . c p p
individual numbers held
in an array. The Create a header file S e a r c h C o u n t V a l . h
numbers in the array
should be randomly
generated. The output Step 1
should be as shown in Write the program, creating an array of random
Figure 73. numbers. Create a small array of 1 5 elements and
add random numbers to the array using the r a n d
function. The random numbers should be between 0
and 1 4 .
You will need to # i n c l u d e < c s t d l i b > for rand()

Step 1
The user should be prompted to enter a number.
Search the array until the number is found or the end
of the array is reached.
Provide an output indicating whether the value is
present or not in the array.

November 2013 79 OUCS


DPFE C++

Step 1
Create a second array that will store in each element a
count of the number of times each randomly
generated number appears in the first array i.e. if 10
appears twice in the array of randomly generated
numbers, element 10 in the second array should show
2.
Make sure your array size is 15 elements and the
randomly generated numbers in the first array are
between 0 and 14.
Output the contents of the second array to screen as
shown in Figure 73
The input and output should be in a loop so the user
can test the program repeatedly. Remember to add a
statement to terminate the program.

Figure 73

Physics/ITLP 80 November 2013


C++ DPFE

9.3. Sorting Arrays with Insertion Sort


When working with large quantities of data in an array you will need to sort the
data at some point. This makes searching for information quicker and there are
many algorithms available that can be used. In the following exercise you will
learn how to sort numbers stored in an array in ascending order.

Exercise 21 Sorting an array


 Create a new project, call it I n s e r t i o n S o r t C l a s s
 Add a header file to the project
 Examine how an array is sorted
 Modify the program, creating a source file to use the class information
Note: Please attempt task 1 and 2 after completing the chapter on classes
OPTIONAL

Task 1 Step 1
Create a new From the directory where you unpacked the
project, call it Inserti source materials, open the file called Insertio
onSortClass n S o r t . h and add it to your project.
Examine the code. The class file is used to sort an
array of integers passed from the main() program
The sort works by first looking at array elements
s o r t [ 0 ] and s o r t [ 1 ] . If the first two values are in
order the program continues otherwise they are
swapped.
In the second iteration the program looks at element
s o r t [ 2 ] and compares this to s o r t [ 1 ] . If the value in
s o r t [ 1 ] is greater than the value in s o r t [ 2 ] the values
are swapped. The while loop is then used to compare
the value in s o r t [ 1 ] to the value in s o r t [ 0 ] .
This iterative process continues until all array
elements have been sorted.

Task 2 Step 1
OPTIONAL Add # i n c l u d e " I n s e r t i o n S o r t . h "
Add a new source file to Create an instance of the class S o r t A r r a y m y A r r a y ;
the project call it Create an array of 200 randomly generated numbers,
InsertionSort.cpp numbers[i] = (1 + rand()%100);

November 2013 81 OUCS


DPFE C++

Step 1
Call the class member function
myArray.sortArray(numbers,SIZE);
Output the sorted array
cout<<setw(4)<<numbers[i];
See Appendix 24.8 for more detail on formatting
output.
Figure 74 and Figure 75 show the array before and
after sorting.

Figure 74

Figure 75

Physics/ITLP 82 November 2013


C++ DPFE

Task 4
Create a second object,
call it y o u r A r r a y .
Create an array of 50
randomly generated
integers between 1 and
50.
Output this array before
being sorted and after
being sorted.
Output a count of the
number of times each
number appears in the
sorted array.

9.4. Multidimensional Arrays


Multidimensional arrays with two dimensions (arrays can have more than two
dimensions) consist of data arranged in rows and columns, see Table 3.
Each element in the array is identified by using two subscripts as shown in Table
3. The first subscript identifies the element row and the second identifies the
element column. a[0] [1] identifies a value in Row 0, Column 1.
The array in Table 3 contains two rows and three columns and can be called a 2
by 3 array.
Column 0 Column 1 Column 2
Row 0 a[0] [0] a[0] [1] a[0] [2]
Row 1 a[1] [0] a[1] [1] a[1] [2]
Table 3

A multidimensional (2 by 3) array of doubles is shown in Table 4.


Column 0 Column 1 Column 2
Row 0 23.67 67.92 85.57
Row 1 12.76 91.32 27.89
Table 4

November 2013 83 OUCS


DPFE C++

Exercise 22 Creating a multidimensional array


 In eclipse, open the project MultiDimenArray
 Examine how values are written into and read from the array
 Modify the program to read in 5 exam marks and

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project MultiDimArra
y Run the program adding 2 exam results for each of
the two students. The output should be similar to
There is one associated Figure 76.
file
MultiDimArrayMain.c
pp

Figure 76
Task 2 Step 1
Examine the code used Examine the following code segments
to write values to and
d o u b l e E x a m M a r k s [ 2 ] [ 2 ] = { 0 } ; This statement
read from a
creates a two-dimensional array having two rows and
multidimensional array.
two columns and initialises the elements to 0.
Every element in the array is identified by an element
name in the form a [ x ] [ y ] , where a is the name of the
array, and x and y are the subscripts that uniquely
identify each element in a . Notice that the names of
the elements in row 0 all have a first subscript of 0 ,
see Table 5. The names of the elements in column 1
all have a second subscript of 1 .
N o t e : multidimensional arrays can have two or more
dimensions (subscripts). Three-dimensional arrays
are uncommon.
Column 0 Column 1
Row 0 a[0] [0] a[0] [1]
Row 1 a[1] [0] a[1] [1]
Table 5

Physics/ITLP 84 November 2013


C++ DPFE

Step 1
Examine the following code segment used to read
values in to the array
for(int row = 0; row < 2; row++)

for(int col = 0; col <2;col++)

cout<<"Enter Exam Mark No "<<col +

1<<" for student No "<<row +1 <<" ";

cin >> ExamMarks[row][col];

cout<<endl;

The two f o r loops work taking one row at a time (the


outer f o r loop) and looping through the columns in
that row (the inner f o r loop). When the marks have
been entered for all the columns in row 0, row 1 is
selected and values entered for each column cell in
row 1.
Table 6 shows how four results would be allocated in a
2 x 2 multidimensional array.
Exam mark 1 Exam mark 2
Stud 1 67 71
Stud 2 61 58
Table 6

Step 1
Examine the following code segment used to calculate
the total of each student’s marks.

if(row ==0)
r1total += ExamMarks[row][col];
else
r2total += ExamMarks[row][col];

r1total is a variables to hold the sum of values in


column 0 and 1, for row 0 (Stud1).
r2total sums the values in the columns for row 1 (Stud
2).

November 2013 85 OUCS


DPFE C++

Selection for each row is made with if(row ==0), this


is Stud1. If row is not 0 then row must be 1 and the
mark can be added to r2total. If three exam marks
were input per student the code for selecting the
marks would need to change.

Task 6
Modify the program to
read in 5 exam marks for
four students.
Establish the highest,
lowest and average mark
for each student. Output
the results.
Establish the highest and
lowest marks overall.
Output the results.
Task 7 Step 1
Create a new A multi-dimensional array has been created and
project, call it Matrix initialised with 80 integers. From the directory where
Manipulation. you unpacked the source materials, open the file
This program will called m a t r i x . t x t . Add this to your program.
manipulate a matrix of The output from the program should be the same as
integers. Each row of shown in Figure 77.
data is totalled and
appended to the row.
Each column of data is
totalled and appended to
the column.
The sum of the contents
of the entire array are
calculated and added
between the row and
column totals

Figure 77

Physics/ITLP 86 November 2013


C++ DPFE

9.5. Declaring and using vectors


Vectors are declared indicating the type and number of elements in the following
way:
vector<type>vectorName;
vector<type>vectorName(initialSize);
vector<type>vectorName(initialSize, elementValues);
Examples are:
vector<double> inNumbers; a vector called i n N u m b e r s with no initial size
to hold d o u b l e s .
vector<char> Name(20); a vector called N a m e with an initial size 20 to
hold characters.
vector<int> ExamMarks(4,6); a vector called E x a m M a r k s holding integers
with initial size of 4 elements each with the
value 6
N o t e : In previous exercises you have created your own member functions. In
the following exercises you will use some of the v e c t o r class member functions
found in the Standard Template Library (STL). Some of these are b e g i n ( ) ,
e n d ( ) , e r a s e ( ) , and s i z e ( ) . See section 24.13 for more detail.
The STL also includes a large collection of a l g o r i t h m s that manipulate the data
stored in containers (vectors are one of several types of container).

You can sort the order of elements in a vector (v e c ) for example, by using the
s o r t algorithm.
sort(vec.begin(), vec.end());

You can find a value (69) in a vector by using the f i n d algorithm.


ptr = find(vec.begin(), vec.end(), 69); p t r is an iterator to store the
memory location of the
element found.
You can reverse the order of elements in a vector, for example, by using the
r e v e r s e algorithm.
reverse(vec.begin(), vec.end());

There are two important points to notice about the call to r e v e r s e . First, it is a
g l o b a l function (as are f i n d and s o r t ) not a member function. Second, it takes
two arguments rather than one and operates on a range of elements, rather than
on the container (vector container in this case).
With the above examples the range is the entire container from b e g i n ( ) to e n d ( )
(vec.begin() to vec.end()). r e v e r s e , like the other STL algorithms, is
decoupled from the STL container classes. The r e v e r s e algorithm can be used to
reverse elements in v e c t o r s , in l i s t s (another container), and even elements in
C arrays.

November 2013 87 OUCS


DPFE C++

The following program is also valid in C++.


int myArray[]={1,6,20,4};;
reverse(myArray, myArray + 4);
for (int i = 0; i < 4; ++i) /*lets see the reversed array*/
cout << "Array[" << i << "] = " << myArray[i];

In the above example the first argument to reverse is a pointer (pointers are
covered in Section 11 but for now we can say the first argument points to the
address in memory that is the start of the vector) to the beginning of the range,
and the second argument points one element past the end of the range. This
range is denoted (myArray, myArray + 4);
Arguments to reverse are i t e r a t o r s , which are a generalization of pointers which
is why it is possible to reverse the elements of a C array using the array address
and pointer notation.

Exercise 23 Creating a vector to hold exam results


 In eclipse, open the project VectorDemo
 Examine how values are written into a vector
 Modify the program to read in additional exam marks
 Modify the program to remove exam marks

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project VectorDemo
Run the program adding five exam results. The
There is one associated output should be similar to Figure 78.
file V e c t o r D e m o . c p p .

Figure 78

Physics/ITLP 88 November 2013


C++ DPFE

Step 2
Examine the following statements
# i n c l u d e < v e c t o r > ; This statement includes the
header file < v e c t o r > enabling the program to use the
class template v e c t o r . (templates allow the use of
generic functions that admit any data type as
parameters and return a value, more on this later.).
v e c t o r < d o u b l e > E x a m M a r k s ( 5 ) ; This
statement declares the vector to hold doubles and sets
the initial size to 5 elements.
N o t e : Although vectors can grow to any size it is
good practice and more efficient to specify the size
when this is known. When no size is given and the
contiguous memory spaces have been exhausted the
elements must be copied to a larger memory space to
increase the size of the vector.
c i n > > E x a m M a r k s [ i ] ; This statement reads in the
user input and stores the values in the vector slot i of
E x a m M a r k s [ i ] . i is incremented within the f o r loop
in a similar way as in the previous array exercises
using the subscript operator [ ] .

Task 2 Step 1
From the directory Copy the code from V e c t o r . t x t and add it to
where you unpacked the V e c t o r . c p p immediately above the return
source materials, open statement ;
the file called
Run the program entering 5 numbers. Follow the
V e c t o r . t x t . Copy the
prompts and add an additional number to the vector.
code and add it to
The output should be as shown in Figure 79.
Vector.cpp
Examine the following statement
ExamMarks.push_back(test);
p u s h _ b a c k ( ) is a member function of the vector
class that adds an additional vector element at the end
and passes the variable test as a parameter to the
vector.
The size of the vector is now six elements.

November 2013 89 OUCS


DPFE C++

Figure 79

s i z e ( ) is a member function of the vector class. It can


be used to establish the size of a vector.
The statement f o r ( i n t i = 0 ; i <
E x a m M a r k s . s i z e ( ) ; i + + ) uses the vector member
function s i z e ( ) available to the vector E x a m M a r k s
to obtain the size (number of elements) in the vector.
The size of the vector is used to identify a terminating
value that ends iteration of the f o r loop.

Task 4
Modify the program to
delete the last element
and output the vector
slots showing all values.
p o p _ b a c k ( ) is the
member function that
can be used to delete the
last element in a vector.

Task 5
Create a new
project, call it Vector
Sort.
In the program create a
vector of 100 randomly
generated numbers.
Output the contents of
the vector before and
after sorting.
See Appendix 24.13 for
more detail on vectors.

Physics/ITLP 90 November 2013


C++ DPFE

Exercise 24 Create a vector of objects


 Create a new project that will allow the user to input details of research
done on penguins. Detail will initially be kept on the penguin type and
colour; more detail will be collected later.

There are many types of penguin and the data for each type will be kept
in instances of a class and the objects stored in a vector.

Task 1 Step 1
Create a new In main() create a vector of penguin objects:
project, call it
vector<Penguins> myPenguin(2);
VectorofPenguins.
Create a header file Print out the default contents of the vector
P e n g u i n s . h and add Loop through the vector adding two objects
member functions to for(int b = 0; b < 2; b++)
allow the user to add and
change the penguin type {
and colour. //Read in the penguin type and colour
Add the necessary
constructors and
/*create first object*/
destructors including a
default constructor that myPenguin[b] = Penguins(name, colour);
will name a type as }
"King" with a colour
"Black, Grey & Orange"
when called.
You will need data
members to store these
values.
In m a i n ( ) add a vector
to store each object
instantiated.
Add two objects using Figure 80
code similar to that
shown in step 1 then add
another penguin object Object member functions can be accessed using the
using vector member following notation.
functions.
Output the contents of cout<<myPenguin[a].getName()
the vector to screen, it
should be similar to
Figure 80.

November 2013 91 OUCS


DPFE C++

Exercise 25 Using the insert() member function and iterators


 Open Insert and examine the program.
 Identify how the insert() member function is used to add data to a vector
at any vector element position.
 Learn how to insert vector data to another vector using the insert()
member function.
 Add an array to a vector using the insert() member function
Task 1 Step 1
Open I n s e r t . Examine the code shown in Figure 81
Only parts of the
program are explained
as much of the program
has been covered in Figure 81
previous exercises.
This statement creates an iterator that is used to
Important areas of the access members of the vector.
program are explained in
the steps. Iterators are used to access members of the container
classes (the container type v e c t o r in this case), and
can be used in a similar manner to pointers (see Sec
11).

In the example shown in Figure 83, iterator i t is used


with the i n s e r t ( ) function to place the value (200) at
the beginning of the vector n u m s .

Examine the code shown in Figure 82

Figure 82

This statement uses the vector member function


b e g i n ( ) to initialise the iterator i t with the address of
the start of the vector.
Examine the code shown in Figure 83

Figure 83
This statement uses the member function i n s e r t ( )
and iterator i t to insert 200 at the beginning of the
vector (i t ).
Note that an iterator is returned by the function
i n s e r t ( ) that points to the newly inserted element.

Physics/ITLP 92 November 2013


C++ DPFE

Step 1
Examine the code shown in Figure 84

Figure 84

This version of the i n s e r t ( ) function takes 3


arguments and is used for copying in part or full
another collection. This may be a vector, a plain C++
array or some other collection that is accessed using
pointers/iterators.

This statement inserts a second vector (n u m s T w o )


into n u m s . The three parameters are: (copy to
nums+1, from start of numsTwo, to end of numsTwo)

Step 1
Examine the code shown in Figure 85

Figure 85

This version of the i n s e r t ( ) function takes 2


arguments. The iterator i t + 2 points to element
number three. i t points to the beginning of the vector
and the 2 moves two elements in. The value 6 9 6 is
inserted at that element.

Examine the code shown in Figure 86

Figure 86

Function Display is passed a reference to a vector and


outputs the vector contents used throughout program.

November 2013 93 OUCS


DPFE C++

Task 4
Add the code shown in
Figure 87 to the program
and using the i n s e r t ( )
member function add
the array to the n u m s Figure 87
vector. Output the
contents of the n u m s
vector to screen.

9.6. Declaring and using lists


Lists are a kind of sequence container similar to vectors. The elements of a list
are ordered following a linear sequence with storage handled automatically by the
class.
List containers are implemented as doubly-linked lists and it is worth noting that
elements may be in different and unrelated storage locations.
Ordering of a list is kept by a relationship to each element of a link to the element
preceding it, and a link to the element following it.
Because linking information is associated with each element (possibly to different
and unrelated storage locations) extra memory may be used to keep the linking.
This may be important when using a large list.
l i s t s tend to perform better than vectors at inserting, extracting and moving
elements in any position within the container but lack direct access to the
elements by their position and because of this have a slower access time than
vectors. Access to an element has to be via a known position (the beginning or
the end) and there is a time cost in linking between the known position and the
element to be accessed.

lists are declared indicating the type and number of elements in the following
way:

list<type> listName;
list<type> listName(initialSize);
list<type> listName(initialSize, elementValues);

Examples are:
list<double> inNumbers; a list called i n N u m b e r s with no initial size
to hold d o u b l e s .
list<char> Name(20); a vector called N a m e with an initial size 20 to
hold characters.
list<int> ExamMarks(4,6); a vector called E x a m M a r k s holding integers
with initial size of 4 elements each with the
value 6

Physics/ITLP 94 November 2013


C++ DPFE

N o t e : In the following exercises you will use some of the l i s t class member
functions found in the Standard Template Library (STL). Some of these are
b e g i n ( ) , e n d ( ) , s o r t ( ) , and s w a p ( ) .
The STL also includes a large collection of a l g o r i t h m s that manipulate the data
stored in lists. See section 24.14 for more detail.

Exercise 26 Merging lists


 In eclipse, open the project Merge
 Examine how values are written into a list
 Modify the program to copy lists

Task 1 Step 1
In eclipse, open the Examine the statement shown in Figure 88
p r o j e c t M e r g e , and
examine the program
works.
Figure 88
This statement creates two lists to hold doubles,
l i s t O n e and l i s t T w o .

Examine the statement shown in Figure 89

Figure 89
This statement creates a third list and initialises it
with two elements each holding 9.69.

November 2013 95 OUCS


DPFE C++

Step 1
Examine the statement shown in Figure 90

Figure 90
This statement creates an iterator for looping through
lists. The iterator type for a l i s t is bidirectional. Note
that the iterator type for a v e c t o r is random access.
The twelve statements following the iterator
declaration use the class member function
p u s h _ b a c k ( ) to add new elements at the end of each
list.
The p u s h _ b a c k member function is common to
vectors and lists.

Step 1
Examine the statement shown in Figure 91

Figure 91
This statement uses member function s o r t ( ) to sort
listOne.
Note that lists do not use the sort algorithm that we
used with the vector class as the sort algorithm only
works with random access iterators, the type used
with vectors.
Lists use bidirectional iterators so there is a member
function l i s t O n e . s o r t ( ) provided.

Physics/ITLP 96 November 2013


C++ DPFE

Step 2
Examine the following statements

Figure 92
list iterator i t is used to loop through the elements of
the list.
l i s t O n e . b e g i n ( ) returns an iterator to the beginning
of the list.
l i s t O n e . e n d ( ) returns and iterator to the end of the
list.
i t and the dereference operator * are used to output
the values in the vector, * i t .

Step 3
Examine the following statement

Figure 93
This statement merges the second list into the first
list.
All the elements of the second list are inserted into the
first list at their respective ordered positions.
N O T E : This empties the second and increases the
size of first list.

Task 4 Step 1
In this task you are The l i s t T h r e e o b n e c t i s r e s i z e d t o to the same
asked to examine size as l i s t T w o using the list member function
m a i n M e r g e . c p p which r e s i z e ( ) so that the list can hold all the elements
copies the contents of copied.
l i s t T w o to l i s t T h r e e .
Arguments to r e s i z e are the size of l i s t T w o . The
Note that c o p y is an l i s t T w o member function s i z e ( ) is used to get this
algorithm not a member value.
function of the list class.
Copy the contents of l i s t T w o to l i s t T h r e e
The syntax for the copy algorithm is:
iterator copy( iterator start, iterator end,
iterator destination );
The return value ‘i t e r a t o r ’ is an iterator to the
destination of the last element copied.

November 2013 97 OUCS


DPFE C++

10 More on Functions
Functions are used to encapsulate a set of operations and return information to
the main program or calling routine. Encapsulation is data, information or detail
hiding.
Once a function is written, the detail of how it works is not important to the end
user. The user needs to understand what data to input and what output will be
produced.

10.1. Multiple arguments and default values

In the following exercise you will pass multiple arguments to a function. The
arguments must be specified in the prototype, each argument is separated by a
comma. The exercise will also detail how to add default arguments in the
prototype.

Exercise 27 Functions with multiple arguments and default values


 Write a program to calculate take home pay using functions and default
argument values

Task 1 Step 1
Create a new The function prototype you create should be similar to
project, call it Salary
. Name the source file void CalcSalary(double grossSal, double IT,
Salary.cpp. double NI = 5.0);
The program should N o t e : In this prototype we are passing multiple
read in a g r o s s s a l a r y arguments. Each argument is separated by a comma.
and rate of Income Tax
A default argument double NI = 5.0 has been also
(I T ).
used in the prototype above. Default arguments must
The s a l a r y , I T and be declared at the end of the list of arguments.
National Insurance rate
Because we are using a default argument for the
(N I ) will be passed to a
national insurance rate it is only necessary to read in a
function to calculate and
gross salary and the rate of income tax.
display the take home
pay. Gross salary and income tax are passed to the function
from main() in the statement
Take home pay is
C a l c S a l a r y ( g r o s s S a l , I T ) ; along with the default
calculated as follows:
NI argument specified in the prototype.
TakeHomePay =
(grosspay*(1-NI))*(1- All three arguments are used in the function to
Income Tax) calculate the take home pay.
Remember, default arguments must be declared at the
end of the list.

Physics/ITLP 98 November 2013


C++ DPFE

Step 2
Create a function call it c a l c S a l a r y
The function will receive three arguments, the
definition is shown below
void CalcSalary(double grossPay, double IT,
double NI)
The formula for calculating the take home pay is:
TakeHomePay = (grossPay*(1-NI))*(1-IT);

I T is the income tax rate read in as a percentage, and


NI is the rate of national insurance at 5 % as specified
in the prototype. The take home pay should be output
from within the function.
Task 2
Modify the program
S a l a r y . c p p to read in
the gross salaries of five
members of staff.
Calculate the take home
pay and display.

Task 3
ONLY ATTEMT THIS IF
YOU HAVE
COMPLETED
CHAPTER 7
Create an o b j e c t for
each member of staff.
Create separate member
functions to change the
rate of N I and I n c o m e
Tax.

10.2. Returning values from functions


One of the most important aspects of writing programs using functions is that the
functions can be reused from one project to the next. In previous programs the
output has been from within the function.
The functions used in previous exercises should really only be used to compute
the change in temperature or calculate take home pay. The result of the
calculation should be returned from the function and not output from within the
function.
Returning values in this way allows the reuse of the function and calculations
contained in it.

November 2013 99 OUCS


DPFE C++

Exercise 28 Returning a value from a function


 Examine and understand how to return values from a function
 Modify an existing program
 Create additional projects

Task 1 Step 1
In eclipse, open the Run the program. The output should be the same as
project Temperature shown in Figure 94.
s R e t V a l u e s and
modify the program.

Figure 94

Step 2
Examine the function prototype
int FtoCent(int temp, int ch);
This function prototype has a return type of int.
When the function is called and calculations
completed an integer is returned to the calling
statement.

Step 3
Exam the calling statement
retValue = FtoCent(I_far, choice);
The function call F t o C e n t ( ) passes arguments I _ f a r
and choice. The value returned is assigned to
retValue

Step 4
Examine the function definition. The function
definition matches the prototype indicating two
integers are being passed to the function and an
integer is being returned.
int FtoCent(int ITemp, int ind) {}

Physics/ITLP 100 November 2013


C++ DPFE

Step 5
Examine the function body. The two statements
below convert the temperature input. The conversion
type required is identified using the user input i n d
and i f selection.
The statement I _ f a r = ( I T e m p - 3 2 ) * 5 / 9 ; is
used to calculate the temp in centigrade
The statement I _ f a r = s t a t i c _ c a s t < i n t > ( I T e m p *
1 . 8 + 3 2 ) ; is used to calculate the temp in farenheit.
The last statement in the function is return I _ f a r ;
This statement returns the temperature I _ f a r to the
calling statement in m a i n ( ) .
N o t e : The data being returned must be the same data
type as defined in the function prototype. In this
example an integer.

Task 6 Step 1
(REQUIRES Modify the program so take home pay is returned
COMPLETION OF 27) from the function and output to screen from within
main().
Open the S a l a r y project
you created in Exercise If you completed Exercise 27Task 2, you will need to
27 Functions with add a member function of the class to achieve this.
multiple arguments and
default values.
Task 7
OPTIONAL
Create a new project, call
it
ReturnExperResults
The program will read in
5 experimental results.
Read the results in to the
main program and pass
them to a function.
The function should
calculate the maximum
value. This should be
returned and displayed
within main.

November 2013 101 OUCS


DPFE C++

Exercise 29 Classes and functions


OPTIONAL
 Create a class file to calculate the average of results

Task 1
Open the project you
created in the last task,
ReturnExperResults,
Exercise 28 Task 7.
Create a class call it
E x p e r i m e n t r e s u l t s in
a new file called
ReturnExpResults.h.
The values read in to
m a i n ( ) should be passed
to a function called
readNumbers( ) in
main().
From within the function
readNumbers( )
create an object of the
class
Experimentresults.
From within the function
pass the values read in to
a constructor of the
class.
The average value
should be calculated
within class member
functions. Use member
functions to return
values to the calling
function.
The average mark should
be returned to m a i n ( )
from the function
r e a d N u m b e r s ( ) , then
output to screen.

Physics/ITLP 102 November 2013


C++ DPFE

10.3. Passing Arrays to Functions


To pass an array to a function, it is only necessary to pass the array name and the
number of elements in the array.
The array name is the position in memory of the first element. The number of
elements is passed to enable the function to establish the array size.
An array declared as double TempReadings[10]; would require a function call,
FunctionName(TempReadings, 10);

Exercise 30 Passing Arrays to functions


 Write a program to pass an array to a function
 Read values into the function
 Calculate the average of values read in
 Output the array values from within main()

Task 1 Step 1
Create a new project, call Create a new project, call it call it
it A r r a y R e t u r n V a l u e . ArrayReturnValue
Pass an array to a Create a function prototype d o u b l e
function and read in five calcAverage(double ExamMarks[], int num);
numbers. E x a m M a r k s [ ] is the array being passed. As with
Calculate the average passing variables, it is not strictly necessary to pass
value in the array, return the name of the argument, just its type. This could
this to m a i n ( ) and have been written as c a l c A v e r a g e ( d o u b l e [ ] , i n t
output to screen. n u m ) ; However, it is useful for future reference as it
helps explain how the function works.
At the end of the
program output the It is also necessary to pass the size of the array. n u m
values in the array from is the number of elements in the array, it’s size.
within m a i n ( ) . Step 2
Within m a i n ( ) declare the array and initialise the
elements to zero with the following statement d o u b l e
ExamMarks[5] = {0};
This declaration explicitly initialises the first element
to zero and implicitly initialises the remaining four to
zero

Step 3
Create a function d o u b l e c a l c A v e r a g e ( d o u b l e
ExamMarks[], int num) { }
Read in the values and calculate the average
Add the code to establish the average of values in the
array
Return the average value to main() and output

November 2013 103 OUCS


DPFE C++

Step 4
Call the function from within m a i n ( ) with the
following statement
average = calcAverage(ExamMarks, 5);

Step 5
At the end of m a i n ( ) add the statements
for(int i = 0; i < 5; i++)
cout<<"Exam Mark Number "<<i + 1<<" is
"<<ExamMarks[i]<<endl <<endl;

Step 6
Explain how it is possible at the end of the program to
output from within m a i n ( ) all the values in the array
entered within the function
In previous exercises when parameters (variables)
were passed to functions the function received a
v a l u e . When a v a l u e is used in a function a copy is
stored in a part of memory that only exists from the
time the function is called to when it ends. After this,
the memory and any v a l u e in it are lost.
However, the array in this exercise was initialised in
m a i n ( ) with zeros and then passed to the function.
Data was then added to the array and calculations
done. At the end of mai n ( ) the values in the array
elements are output. The array contains values input
from within the function.
When the function is called
c a l c A v e r a g e ( E x a m M a r k s , 5 ) the name of the
array, E x a m M a r k s is passed.

Physics/ITLP 104 November 2013


C++ DPFE

The name of the array is the a d d r e s s in the computer


memory of the first element of the array. As the
starting address is passed (the name of the array), the
called function knows where the array is stored in
memory.
Because we are working with memory addresses
(r e f e r e n c e s ) any changes made to array elements in
the function affect the memory location set up in
m a i n ( ) for the array.
C++ passes arrays to functions by r e f e r e n c e (to the
memory location of the first element). In previous
exercises functions were passed v a l u e s , copies of the
variables in m a i n ( ) .

Task 8
Modify your program so
that the calculations are
done in a class file. Pass
the array to the class
using a constructor.

Task 9
Go back to Exercise 21
and modify the header
file to sort the array
passed using the global
vector function s o r t ( ) .
You should be able to
replace the whole
member function
functionality with one
statement.
N o t e that you will have
to change the class
member function name
from s o r t to another
name. Defining a
member function name
the same as a vector
function name will cause
a compilation error.
Choose your own
function name or use
sortArray().

November 2013 105 OUCS


DPFE C++

Task 10
Continuing from the
previous task, when you
have sorted the array
add another member
function to reverse the
array.
Call the new member
function and check the
array has been reversed.

Physics/ITLP 106 November 2013


C++ DPFE

10.4. Passing Two-dimensional Arrays to Functions


It is common to want to store numbers in a two dimensional layout of rows and
columns as shown in Table 7.

1876.45 7834.73 2983.72


8712.23 6293.99 5612.01

Table 7

This arrangement is known as a two-dimensional array or matrix.


C++ uses an array with two subscripts to store a two dimensional array.
double Balance[2][3];
When we specify a one-dimensional array the number of elements must be given.
When a two-dimensional array is specified it is necessary to specify the array
elements in both dimensions. We therefore specify the number of rows and
columns.
The B a l a n c e array in the statement above has two rows and three columns.

Exercise 31 Multi-Dimensional Arrays and functions


 Write a program to pass a multi-dimensional array to a function
 Read bank deposits in
 Calculate the deposits, interest and total capital for all customers
 Output the array values from a function

Task 1
Create a new project, call
it call it
ArrayMultRetVal.
The program will read in
bank account deposits
for two customers and
output the balance of
accounts.
The customer will be
prompted to enter
deposits and these will
be stored in a two-
dimensional array. Figure 95

November 2013 107 OUCS


DPFE C++

The output to screen will Step 1


show the total sum Before m a i n ( ) create a function prototype,
invested, the interest void getDeposits(double Balance[]
accrued and the balance [colSize],int );
after addition of interest
for each customer. This statement indicates there is a function that will
be passed a 2 dimensional array with 3 columns. The
The last line of output number of rows and columns is determined within
will show the overall main().
sum of all accounts
Create a second prototype void
before interest is added, passBalances(double Balance[]
the sum of all interest [colSize],int );
and total balance for
each customer. See This is used to do calculate balances and output to
Figure 95. screen.
The array will be Declare two constants for the rows and columns
declared in m a i n ( ) and b e f o r e the function prototypes.
passed to two functions.
const int rowSize =2;
The first function will be const int colSize =3;
used to get user deposits,
the second to do the the c o n s t qualifier can be used to declare a constant
calculations and output variable r o w S i z e to 2 .
to screen.
N o t e : constant variables must be initialised and
cannot be changed. These are declared outside
m a i n ( ) and can be seen by all functions.

Within m a i n ( ) declare the array and initialise the


elements to zero.
double Balance [rowSize] [colSize] = {0};
Create the function g e t D e p o s i t s ( ) after m a i n ( ) .
The function definition should be:
void getDeposits(double Balance[]
[colSize],int rS)
{

/*add deposits in here*/

See section 9.4 Multidimensional Arrays for detail on


how to add the deposits in the function.

Physics/ITLP 108 November 2013


C++ DPFE

Step 2
Create a second function v o i d p a s s B a l a n c e s
( d o u b l e B a l a n c e [ ] [ c o l S i z e ] , i n t r S ) after m a i n ( )
Calculations to establish the interest and balance for
each customer should be done in the inner loop
(c o l u m n ) of the array search. The following
statements will establish the deposit, interest and
total for each deposit
deposited += Balance[r][c];
interest +=Balance[r][c]*0.05;
total +=(Balance[r][c]*(1 + 0.05));
The calculations to total all deposits need to be done
in the outer loop (r o w s ) of the array search
OAdeposited += deposited;
deposited = 0; /*reset the amount deposited
for next customer*/
OAinterest +=interest;
interest = 0; /*reset the interest for next
customer*/
OAtotal +=total;
total = 0;
Step 3
Call the functions from within main() with the
following statements.
getDeposits(Balance, rowSize);
passBalances(Balance, rowSize);

Task 5
Modify the program you
have just created using a
class defined in a
separate header file.
Pass the array to the
class object.
All calculations should
be done within the class
file and output via
member functions.

November 2013 109 OUCS


DPFE C++

10.5. Overloading functions


When the same name is used for more than one function the function name is
overloaded. C++ allows several functions to be defined with the same name
provided the functions have different sets of parameters.
The parameters set can be different kinds, or different number of parameters or a
combination of both. When the overloaded function is called the compiler looks
at the type and order of parameters before deciding which function to call.

Exercise 32 Function Overloading


 Examine a program to see how functions can be overloaded

Task 1 Step 1
In eclipse, open the Run the program. The output should be the same as
project Overloading shown in Figure 96.
F u n c t i o n s . Examine
the program structure.
There is one source file
OverLoadingFunction
s.cpp.

Figure 96

Step 2
Examine the function prototypes
void FtoCent(int temp);
void FtoCent(double temp);

Both prototypes return v o i d and both have the same


name. The parameters that are being passed are
different, i n t and d o u b l e .

Physics/ITLP 110 November 2013


C++ DPFE

Step 3
Examine the statement
i n V a l u e = t o u p p e r ( i n V a l u e ) ; t o u p p e r is a
member function in header file < c c t y p e > that
changes the input char to upper case. Using t o u p p e r
means it is unnecessary to test for upper and lower
case values input.

In the selection (i f , e l s e i f , e l s e ) either an inte ger


or d o u b l e is read in, then the appropriate F t o C e n t
function called. The compiler differentiates
overloaded functions by the function name and order
of parameter type. This ensures the proper
overloaded function is called.

Step 4
Examine the function definitions.
The two function definitions have the same name but
different types of argument. In this example the
compiler is selecting the correct function on the single
argument type being passed.

Step 5
Examine the function v o i d F t o C e n t ( d o u b l e
I T e m p ) used to convert a double value read into
centigrade.
The statement c o u t < < f i x e d < < s e t p r e c i s i o n ( 2 ) ;
This statement sets the stream manipulators, f i x e d
and setprecision. Another stream manipulator used
in this function is s e t w . The header file < i o m a n i p >
must be included to use these stream manipulators.
When several numbers are displayed each is printed
with the minimum number of digits needed to show
the value. This can produce some unexpected output
results.
The width of an output field can be set using a stream
manipulator setw. To set the next number to be
printed to a width of 5 digits use c o u t < < s e t w ( 5 ) .
This command does not produce any output but
manipulates the stream to change the output format
of the next value. Note: setw must be specified for
every item output.

November 2013 111 OUCS


DPFE C++

The statement c o u t < < f i x e d < < s e t p r e c i s i o n ( 2 )


< < s e t w ( 5 ) < < I T e m p ; sets the precision of the
following floating point number to 2 decimal places
and the field width to 5.
As f i x e d and s e t p r e c i s i o n only have to be used
once, the above statement could be written as two
statements c o u t < < f i x e d < < s e t p r e c i s i o n ( 2 ) ;
c o u t < < s e t w ( 5 ) < < I T e m p ; avoiding repetition of
f i x e d and s e t p r e c i s i o n with further statements.
See Appendix 24.8 for more detail.
Task 3 Step 1
Modify the program in Modify the program O v e r L o a d i n g F u n c t i o n s
the previous task so the
The formula for converting from Centigrade to
program can be used to
Fahrenheit is f = ( ( 9 * c ) / 5 ) + 3 2 . 0 ; f is the
convert temperatures
temperature in Fahrenheit and c is a temperature in
from Centigrade to
Centigrade.
Fahrenheit as well as
from Fahrenheit to
Centigrade.

Overload the new


function so the user can
enter an integer or
double to the program.
Task 4
OPTIONAL
Add a class header file to
the project. Call it
OverLoadingFunction
s .h.
Modify the program so
the calculations are done
within a class header file.

Physics/ITLP 112 November 2013


C++ DPFE

10.6. Function Templates


In the previous section you used overloaded functions to perform similar
operations that required different program logic on different data types. When
the program logic and operations are the same for all data types it is usual to
perform overloading by using function templates.
When using templates the argument types passed to the function can be different
and C++ automatically generates separate object code functions ( f u n c t i o n
t e m p l a t e s p e c i a l i s a t i o n s ) to handle each call in an appropriate way. When a
template is used in this way a whole list of overloaded functions has effectively
been created and the user can enter any data types to match the number of
arguments the function requires.
All function templates begin with the keyword t e m p l a t e followed by a list of
template parameters enclosed in angle brackets t e m p l a t e < t y p e n a m e T > .
The keyword t y p e n a m e indicates that the value T will be a type and not a value.
It can be a primitive type (i n t ) or a class type (s t r i n g ). N O T E : Earlier versions
of C++ used the keyword c l a s s for this purpose and the template prefix would be
written as t e m p l a t e < c l a s s T > . You can use either but the keyword t y p e n a m e
is more descriptive.

Exercise 33 Function Templates


 Examine a program to see how function templates can be used instead of
function overloading

Task 1 Step 1
In eclipse, open the Run the program, adding data as requested. The
project FunctionTem output should be the same as shown in Figure 97
p l a t e . Examine the
program structure.
There are two associated
files:
FunctionTemplate-
Maximum.h
FunctionTemplate-
Maximum.cpp.

Figure 97

November 2013 113 OUCS


DPFE C++

Step 2
Examine the header file F u n c t i o n T e m p l a t e -
Maximum.h

template < typename T >

T maximum( T value1, T value2, T value3 )

All function templates begin with the keyword


t e m p l a t e . The type t e m p l a t e parameter T in the
function template definition is used to specify the type
of argument passed to the function, the return type
and any variables declared in the function.

The t e m p l a t e parameter T precedes the three


arguments being passed, the return type and the
variable m a x i m u m V a l u e declared in the function.

The other selection statements in the header file are


used to establish the maximum value passed to the
template function which is then returned to the calling
program.

F u n c t i o n T e m p l a t e - M a x i m u m . c p p is used to
prompt the user to enter three integers, three doubles
and then three characters. This demonstrates how
one template function can be used instead of function
overloading when the program logic and operations
are the same for all data types.

Task 3 Step 1
Create a new Create two files in the project. A class definition and
project, call it Functi the client code.
onTemplateArrays.
In the header file create the class S h o w A r r a y
In the class create a function template as shown in
Figure 98 (or copy from FunctionTemplate-
Arrays.txt)

Physics/ITLP 114 November 2013


C++ DPFE

Figure 98

Step 2
In m a i n ( ) create three arrays. One with 45 randomly
generated doubles, one with 45 integers and one with
10 strings.
Create an object of class S h o w A r r a y with the
statement S h o w A r r a y m y S h o w A r r a y ;
Call the template function passing the three arrays in
turn.
This shows that when the program logic is the same
for all data types function templates can be used for
function overloading. See Figure 99.

Figure 99

November 2013 115 OUCS


DPFE C++

11 Pointers

In C++ programming data (variables) can be referenced by pointing to the


a d d r e s s of a memory location.
A p o i n t e r variable contains the a d d r e s s (location in memory) of a data variable.
This can be particularly useful when working with arrays as the elements in an
array will always occupy consecutive memory places. Incrementing the pointer
variable by one, addresses the next array element.

Declarations:
int C; This is a standard variable declaration C , that contains a value as yet
unknown of type int.
int *C; This is a pointer C , that will point to an address in memory containing
a value of type int.
Each variable declared as a pointer must be preceded by an asterisk (* ).
int *age, height; a g e is a pointer, h e i g h t is a value.
double *far, *cent; are both pointers to double values.
Pointers must be initialised when they are declared, or in an assignment. It is
common to initialise pointers to a memory address but they can also be initialised
to zero. A pointer pointing to 0 is called a n u l l p o i n t e r .
Note:
When the * is used in a variable declaration it indicates the variable being
declared is a p o i n t e r and not a v a l u e .
But do beware, when the * appears before a pointer variable elsewhere in the
program it acts as an operator, called the d e r e f e r e n c e o p e r a t o r . It causes
tohe program to look up the value that the pointer references – i.e the data stored
at the address of that pointer.
To complicate matters further using the pointer name without the dereference
operator in the program references the address in memory.

11.1. Initialising pointers


Pointers can be initialised in two ways.
int x = 16, y = 69; /*variable declaration and initialisation*/

1: int *x_ptr = &x; /*pointer declaration and initialisation. x p t r


points to the a d d r e s s of x */
2: int *y_ptr; /*pointer declaration. y p t r is a p o i n t e r .*/
y_ptr = &y; /*Pointer initialisation. y p t r points to the
address of y . */

Physics/ITLP 116 November 2013


C++ DPFE

Once declared, a pointer variable can be assigned the address of another variable
using the & “a d d r e s s o f o p e r a t o r ”.
Note: we have seen the & before when declaring references to values. In that
case, we saw it when the value was declared. Here we see its use as an
operator.

Exercise 34 Using pointers


 In eclipse, open the project Pointers
 Examine the structure of the program

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project Pointers.
There is one associated Run the program. The output should be the same as
file, Figure 100.
PointersMain.cpp.

Figure 100

November 2013 117 OUCS


DPFE C++

Step 2
Examine the following statements. Only the
important parts of the program are explained, the rest
has been covered in previous exercises.
int *x_ptr = &x; This is x _ p t r pointer
declaration and initialisation.

int *y_ptr; Declaring another


pointer y _ p t r .

y_ptr = &y; Initialising y _ p t r .

y _ p t r = x _ p t r ; Assigning x _ p t r address t o y _ p t r .
Both pointers are pointing to variable X ( 1 6 ) .

y _ p t r = & y ; Assigning the address of y back to


pointer y _ p t r .

* y _ p t r = 1 7 0 ; Assign 1 7 0 to the variable at memory


location stored in y _ p t r . y _ p t r points to variable y so
1 7 0 has been assigned to y .

11.2. Pointer Arithmetic and Arrays


We have seen that once a pointer is initialised it has a memory address and this
address can be reassigned another address. It is also possible to change an
address using standard arithmetic.
The + + and - - , increment and decrement operators can be used to move the
pointer along to the next, or back to the previous memory address. To jump more
than one memory address you would have to use the assignment operators + =
and - = .
When using arrays and pointers the array name is the address of the first element
in the array.
int intArray[] = {1,2,3,4,5};
int *x_ptr = intArray;

The pointer has been declared and initialised with the statement int *x_ptr =
intArray; Note: there is no need to use the address of operator & when
initialising arrays as the array name is the address of the beginning of the array.
When working with arrays each element of the array will be the type and size at
declaration. When an array is declared to hold integers, each element will be 4
bytes in size. An array of doubles will have element sizes of 8 bytes.

Physics/ITLP 118 November 2013


C++ DPFE

It is not important to know how many bytes make up each element. Moving the
pointer through the array with the assignment operator x _ p t r + = 2 will move
two elements further through the memory allocated for the array, or 16 bytes for
an array of doubles.

Exercise 35 Pointers and Arrays


 In eclipse, open the project PointerArithmetic
 Examine the structure of the program

Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project PointerArith
m e t i c . There is one Run the program. The output should be the same as
associated file, Figure 101.
PointerArithmeticMai
n.cpp.

Figure 101

Step 2
Examine the following statements in the program.
Only the important parts of the program are
explained, the rest has been covered in previous
exercises.
i n t * x _ p t r = i n t A r r a y ; this is the pointer
declaration and initialisation. Note: The name of the
array is the address of the first element.
for (i = 1; i<5;i++)
{
x_ptr++;
cout <<"The VALUE stored in ELEMENT
"<<i+1<<" is " <<*x_ptr <<endl;
}

November 2013 119 OUCS


DPFE C++

The statement x _ p t r + + ; (N o t e : there is no


d e r e f e r e n c e o p e r a t o r therefore x _ p t r is pointing
to a memory a d d r e s s ) moves the pointer one
a d d r e s s further along the array

In * x _ p t r the * is used outside a variable declaration


so it is acting as the d e r e f e r e n c e o p e r a t o r
referencing the v a l u e at a memory location.

x _ p t r - - ; (there is no preseeding d e r e f e r e n c e
o p e r a t o r therefore the pointer is pointing to a
memory a d d r e s s ) moves the pointer one a d d r e s s
back along the array. As this statement is in a f o r
loop that repeats four times the pointer has been
moved back to the beginning of the array.

The statement x _ p t r + = 4 ; moves the pointer four


addresses further into the array. The value there will
be the value in the last element in the array, 5.
Task 2
Create a new project, call
it R e v e r s e A r r a y

In m a i n ( ) create an
array of 20 random
numbers of type double.

Pass the array to an


object’s constructor and,
using only pointer
arithmetic, copy the
external array into a
member variable of the
class.

Using only pointers


reverse the values in the
array of twenty doubles.

Output the reversed array


from within m a i n ( ) .

Physics/ITLP 120 November 2013


C++ DPFE

Task 3 Step 1
Create a new From the directory where you unpacked the
project, call it Array_ source materials, open the file called Array_
Algorithm. Algorithm.txt
Use STL global functions Replace the default source file in the project with
to manipulate an array. Array_Algorithm.txt
Add the necessary code so the output is the same as
that shown in Figure 102.

Figure 102

November 2013 121 OUCS


DPFE C++

The array can be reversed using the algorithm


r e v e r s e ( ) and p o i n t e r s to the beginning and end of
array. A in place of iterator v e c . b e g i n ( ) and A + 6
in place of v e c . e n d ( ) .

reverse(A, A + 6);

A identifies the first element in the array, it points to


the first element. A + 6 points to the last element.
Because r e v e r s e is decoupled from the STL
container classes and works on a range of elements we
are able to use pointers in place of the iterators
v e c . b e g i n ( ) and v e c . e n d ( ) .
Sort the array using the sort algorithm s o r t ( ) and
p o i n t e r s to the beginning and end of array A .

Search the array and store the address if found.


ptr = find( A, A + elements, numToFind );
Check if pointer p t r is past end of the array: i f ( p t r =
= A + e l e m e n t s ) and if it is tell the user.

If the pointer p t r is not past end of array, the number


is there. Output the value using pointer notation * p t r .

See section 24.13 for more information on vectors and


global functions.

Task 4
OPTIONAL
Now you have seen how
to find values in an array
go back to Exercise 21
and add functionality in
a new member function
to allow the user to
search for numbers
repeatedly until they end Figure 103
the program. See Figure
103.

Physics/ITLP 122 November 2013


C++ DPFE

12 Classes and Interfaces


12.1. Interfaces
The interface of a class defines the services a class’s objects can use and how to
request the services. Interfaces do not contain detail of how the class works.
In the programs you have been writing the class definition in the . h files contain
the complete definitions for the member functions and the declarations of the
private data members.
It is considered better practice* to define the member functions separately as
function prototypes that describe the class’s public interface. The data members
of the class are also defined in the interface as memory has to be allocated for
each data member.
The detail member functions implementation, or how they work, is in a separate
source code file.
* In larger projects - when the same classes used in multiple libraries - this separation is essential.
The interface declaration, or the knowledge of how to interact with the class, must be known
wherever it is used. The implementation, or how the class performs its function, may only be
defined once.

Exercise 36 Creating an Interface


 Open an existing project
 Modify a header file
 Create an interface

Task 1 Step 1
In eclipse, open the I n e c l i p s e , o p e n t h e p r o j e c t H e a d e r . If you
p r o j e c t H e a d e r . There do not have this project, go back to Exercise 13 and
should be one associated complete the task.
source file:
OxStudents.h.
Add a new Source file to the project, File | New |
Source File
Modify the header file to
create class definitions. Save and name the file O x S t u d e n t s . c p p .

Create an additional file


detailing the member Step 1
function definitions that Copy the class definition code from O x S t u d e n t s . h
represent the file and paste it into the O x S t u d e n t s . c p p file.
implementation of the
class. Change the code in O x S t u d e n t s . h so there is no
implementation, see Figure 104

November 2013 123 OUCS


DPFE C++

Figure 104

Step 1
Add the directive # i n c l u d e " O x S t u d e n t s . h " at
the top of O x S t u d e n t s . c p p
Compile the program
You should get a compilation error indicating a
redefinition of class O x S t u d e n t s . The class has
already been defined in the . h file and a class
cannot be defined twice.

Step 1
Remove the class definition by removing the line
c l a s s O x S t u d e n t s and the closing curly brace
and semi-colon at the end of the file
Remove p u b l i c :
Change the function headers to match Figure 105 .

Figure 105
Notice that d i s p l a y N a m e is now preceded by the
class name, O x S t u d e n t s and :: the b i n a r y s c o p e
r e s o l u t i o n o p e r a t o r . The member function is
now related to the separate O x S t u d e n t s class
definition that contains the class data members
and member function definitions.
Compile and run the program

Physics/ITLP 124 November 2013


C++ DPFE

Task 6
OPTIONAL
Go back to the other files
you have created and add
interfaces to these projects.

November 2013 125 OUCS


DPFE C++

13 Session 2
13.1. files used

Files & Folders you will need. These are available from:
http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013/EclipseStudentFiles_part2.tgz

Birds
Composition
FriendClass
Friends Function
FuncRefValinline
HumPlacMammal(StudDefinitions)
Inheritance Dynamic
InheritanceStaff
Java.txt
Mult Base Class - StudentTeacher
Multiple Inheritance
Operator Overloading +
Overload STREAM INSERTION
OverRideBaseClassmeths
Polygon
PurVirtualFunctions
RefSalary
RefSalary2
strcatStrncat
Student ATM Abstract Balance Inquiry

Physics/ITLP 126 November 2013


C++ DPFE

14 Inline functions, values and references


14.1. Inline functions
For small functions the execution time involved in the function call (transfer of
control, moving arguments in memory) can be greater than the execution time
required by the body of the function itself.
Placing the qualifier 'inline' before the function return type definition tells the
compiler to generate a copy of the function code in place to avoid a function call.
i n l i n e i n t s q u a r e B y V a l u e ( i n t ) ; shows a function prototype being made
inline.
When an inline function is called the compiler expands the body of the function
in place. This eliminates the execution cost of the function call but results in
multiple copies of the function body. One for each time the function is called. The
compiler c a n ignore the call and for most functions with more than one
statement typically will.

14.2. Functions, call by reference and call by value


In the programs we have created previously, function arguments have been
passed ‘by value’ to a local variable inside the function. The function works with a
copy of the original value.
When we pass a value ‘by reference’ the address of the variable is passed to the
function and the function works with the original value.
The function prototype int squareByReference(int &); is a function
prototype where an argument is passed by reference (int &).
References need to obey certain rules. A reference can never contain a null value,
if we use one the program may compile but it will not perform correctly. For this
reason it is sometimes necessary to use pointers in preference to references.

Rule References Pointers


Can be declared without No Yes
initialisation
Can be reassigned No Yes
Can contain a null value No Yes
Easy to use Yes No
Most efficient Yes No

November 2013 127 OUCS


DPFE C++

Exercise 37 Examine inline functions and call by reference


 Run the program, identify and examine inline functions and reference
arguments. See how global variables with the same name as local
variables can be accessed using the unary scope resolution operator ::

Task 1 Step 1
In eclipse, open the Open the P a s s B y R e f F u n c project.
project FuncRefValInli
ne. Step 1
Examine the structure of Run the program. The output should be as shown
the project to identify in Figure 106.
different inline function
calls, and the use of
pointers and reference
arguments with function
calls.

Figure 106

Step 2
Examine the function prototypes shown in Figure
107.
The first prototype shows passing an integer value
to a function. A copy of the variable is passed to
the function.
The second statement shows passing a reference to
a function. The address of the variable is passed to
the function.
The third statement shows passing a reference to a
function using a pointer. The address of the
variable is passed to the function.
The fourth function prototype shows how a default
argument can be passed to a function. If the user
supplies an argument in the function call this will
override the default argument.

Physics/ITLP 128 November 2013


C++ DPFE

All the functions have been made inline. This tells


the compiler to generate a copy of the function
code in place to avoid a function call.
When the inline functions are called the compiler
expands the body of each function in place. This
eliminates the execution cost of the function call
but results in multiple copies of the function body.
One for each time the function is called. The
compiler can ignore the call but for these calls
probably will not.

Figure 107

Step 3
Examine the variable declarations shown in Figure
108.
The first three statements are standard variable
declarations.
int *wPtr; declares a pointer of type integer.
wPtr = &w; assigns the address of variable w to
the pointer.
int &zRef = z; z R e f is a reference to z .
References must be initialised when declared.

Figure 108

November 2013 129 OUCS


DPFE C++

Step 4
Examine the statement shown in Figure 109. : : is
the u n a r y s c o p e r e s o l u t i o n o p e r a t o r and is
used to access the global variable x (20) with the
same name as the local variable x (20). The local
variable can be accessed using the standard
notation.

Figure 109

Step 5
Examine the rest of the program and then add
z R e f = & w ; as shown in Figure 110.
Compile the program.
Explain what is happening and why the program
will not compile.

Figure 110

Physics/ITLP 130 November 2013


C++ DPFE

14.3. Reference parameters and classes


When we pass class instance objects to functions the object in the function
becomes a separate object from the one passed.
We can say that a value (a copy) has been passed and not a reference to the
original object. Any changes made to the instance data members in the function
are made to a copy of the object, not to the object passed.
If changes need to be made to the object data members passed to the function we
must do things in a different way. A reference to the object must be passed as a
parameter in the function call.
The way this is achieved is similar to passing references to fundamental data
types as seen in Exercise 37.
See Figure 111, Figure 112, and Figure 113.

Figure 111

Figure 112

Figure 113

Figure 111 shows a function prototype with two parameters. A s t a f f object and
double.
Figure 112 shows the function call with an instance of S t a f f called J o h n being
passed with a d o u b l e 1 0 .
Figure 113 shows the function body. It receives the two parameters. The staff
object e m p is set to the same value as John and amount is set to 10. e m p is then
modified but the modification has no effect on John as e m p is a separate object.
When the function exits e m p is forgotten and John doesn’t get a raise, most
unsatisfactory.
I n t h e f u n c t i o n r a i s e S a l a r y ( ) , e m p is a value parameter because it is a
variable initialised with a value supplied by the caller. We want e m p to refer to
the instance object J o h n . We also need the salary of J o h n to be updated with
changes calculated within the function. To achieve this we make e m p a
r e f e r e n c e parameter.

November 2013 131 OUCS


DPFE C++

e m p is not a new variable but is a reference to J o h n . A ny changes to e m p (via


member function calls) actually change the variable to which it refers, in this case
John.
Reference parameters syntax is:

Staff & emp - s t a f f object reference called e m p


int & number - i n t reference called n u m b e r

When parameters are declared in this way they are bound to the variable in a
function call and allow the function to modify the variable.

Exercise 38 Examine and modify class reference parameters


 Run the program and establish how the program works.

Task 1 Step 1
In eclipse, open the Open the S t a f f project.
project RefSalary.
Examine the structure of
project and establish how Step 1
the program works. Run the program. The output should be as shown
in Figure 114.
Modify the program to use
reference parameters so
e m p is a reference to an
existing instance object
John.

Figure 114
Obviously there is a problem somewhere; John
Black has not received the payment with the
increase in salary.

Physics/ITLP 132 November 2013


C++ DPFE

Step 2
Modify the program, to use reference parameters.
This means pass a reference to the instance object
(the address) to the function. Compile and run the
program again
The output should be as shown in Figure 115.

Figure 115
Step 3
The answer is in section 14.2.

14.4. Constant objects and const member functions

The c o n s t keyword allows us to specify whether or not a variable is modifiable.


We can use c o n s t to prevent modifications to variables, pointers and references.
We can also create c o n s t objects and if an object is made constant then all
member functions must be made constant.
Some of the objects we create need to be modified and others don’t. By making
objects and variables c o n s t we ensure that attempts to modify them in the
program are caught at compile time and do not produce errors when the program
runs.

14.4.1 Const pointer or pointer to constant


Pointer declarations let you declare a p o i n t e r t o a c o n s t or a c o n s t p o i n t e r .
const double *x = &a; //pointer to const double
this statement declares x as a pointer object to a c o n s t double. Here the value
pointed at cannot change but the pointer can.
double *const x = &a; //const pointer
this statement declares x as a object of type c o n s t pointer to a double. Here the
value pointed at can change but the pointer cannot.

November 2013 133 OUCS


DPFE C++

Staff *const emp;


this statement declares e m p as a object of type c o n s t pointer to an object of type
S t a f f . Here the instance object pointed at can change but the pointer cannot.
const Staff *const emp;
this statement declares e m p as a object of type c o n s t pointer to a const object of
type S t a f f . Neither the instance object pointed at, nor the pointer can change.

14.4.2 Const reference

After a reference has been declared it cannot be changed. Any attempt to refer
the reference to another object (as we can do with pointers) will cause a
compilation error.
Since we cannot change a reference after it has been defined, a reference must be
assigned to an object when it is declared.

const double &x = a;


declares a reference to a const of type double.

double &const x = a;
declares a constant reference and will cause a compilation error. R e f e r e n c e s
are constant by default.

const Staff &emp = Sarah; //assign ref to Sarah instance


declares a reference to a constant S t a f f instance object.

const Staff &const emp = Sarah;


declares a constant reference to a constant object and will cause a compilation
error. R e f e r e n c e s a r e c o n s t a n t a n d c a n n o t b e c h a n g e d .

14.4.3 Constant member functions

const Shape rectangle(23,87.6);


declares a c o n s t object r e c t a n g l e and initialises the width to 23 and height to
87.6. Any attempt to modify the object will cause a compilation error.

double Shape::getArea() const


{
return area;
}

Physics/ITLP 134 November 2013


C++ DPFE

The function above declares g e t A r e a as a constant member function. The


function cannot modify the object (S h a p e object) in any way. It is effectively a
"read-only" function. All member functions that do not modify the object should
be declared c o n s t , whether the object is a const object or not.
Note that we must add the c o n s t keyword in both the declaration and the
definition. Constant member functions cannot modify any data members or call
any member functions that are not constant.

Exercise 39 Modify constant pointers and references


 Run the program and sort compilation errors.

Task 1 Step 1
In eclipse, open the Look at all the files in the project and modify the
project RefSalary2 program so that c o n s t references, pointers, objects
Examine the structure of and member functions are addressed correctly.
the project and establish
how the program works.
This is very similar to the Step 1
program you used in When the program is compiled the output should
Exercise 38. be as shown in Figure 116 .
The program is using
constant pointers, constant
references and should be
using constant member
functions.
Modify the program so the
const pointers and objects
are being used correctly.
Also check the member
functions have been
correctly written and are
not being used to modify Figure 116
any const data.

November 2013 135 OUCS


DPFE C++

15 More on Classes
15.1. Inheritance
Inheritance is an important feature of classes; in fact, it is integral to the idea of
object-oriented programming.
Inheritance allows us to create a hierarchy of classes. As the hierarchy grows
classes become more specific.
Specific classes inherit the more general aspects of the classes above them in the
hierarchy, see Figure 117.
In this way it is possible to structure a program starting with abstract ideas that
are then implemented by specific classes.

Figure 117
Figure 117 shows a hierarchy of potential classes. Mammals might be one of our
classes. The classes Placental Mammals, Monotremes and Marsupials all inherit
traits that are general to all Mammals. Each of these classes will also have
attributes specific to the Placental Mammals, Monotremes or Marsupial class.
Note also that Mammal is a class derived from Vertebrates and so would inherit
attributes of that class.
As an aside, let’s see what the characteristics of Mammals, Placental Mammals,
Monotremes and Marsupials are. This will help determine the data members and
class member functions we need to add to the three classes.

Mammals.
Mammals are vertebrate animals that are endothermic (warm blooded), have hair
on their bodies, and produce milk to feed their babies.

Physics/ITLP 136 November 2013


C++ DPFE

Placental Mammals
The young of placental mammals develop inside the mother’s body while attached
to a placenta. Some examples of placental mammals are cats, bears, monkeys,
and humans.
Monotremes
Monotremes are the most primitive mammal and there are only three species: the
duck-billed platypus and two species of echidna (spiny ant eaters). These
mammals have hair and produce milk, but they also lay eggs.
Marsupials
Marsupials have tiny undeveloped young that grow inside the mother’s body
instead of in an egg. When they are born, they climb up the mother’s fur to a
pouch on her belly, settle and feed inside. Some well-known marsupials are
koalas and kangaroos

15.2. Inheritance Syntax

Figure 118

The syntax to denote one class as inheriting from another is simple and shown in
Figure 118. This shows a simple change in class declaration from the keyword
c l a s s used previously.
c l a s s C a t : p u b l i c b a s e _ c l a s s _ n a m e is the essential syntax for inheritance.
The syntax indicates that the class (C a t ) will contain all public and protected (see
section 15.3) data members of the base class (P l a c e n t a l M a m m a l s ). This does
not mean derived classes have access to all data members of a base class and the
specific instances of any derived class data.
The members, the variables and functions possessed by the derived class, are
specific to the type of class, not to each individual object of that type. Two
different Cat objects having the same members would most likely have different
information stored in their data members.

November 2013 137 OUCS


DPFE C++

15.3. Public, Private or Protected?


Data members and member functions of the classes you create will have different
levels of access from within its own class and from other classes that interact with
it. Three keywords are used to control access to functions and variables stored
within a class.
 p u b l i c : A data member or member function declared in a p u b l i c section
of a class can be accessed from wherever the class is visible.

This is the most open level of data hiding. Anything that is public is available
to all derived classes of a base class. The public variables and data for each
object of both the base and derived class are accessible by code outside the
class. Functions marked public are generally those the class uses to give
information to and take information from the outside world; they are typically
the interface with the class.

The rest of the class should normally be hidden from the user and be private
or protected. The hidden nature and the highly focused detail of classes is
called e n c a p s u l a t i o n .
 p r i v a t e : A data member or member function declared in a p r i v a t e
section of a class can only be accessed by member functions and f r i e n d s (see
section 15.7) of that class.

Private is the highest level of data hiding. Functions and data members
marked private are not accessible by code outside the specific object in which
that data appears. Note also that private variables and functions are not
inherited, but we can access them using public member (accessor) functions.
 p r o t e c t e d : A data member or member function declared in a p r o t e c t e d
section of a class can only be accessed by member functions and f r i e n d s of
that class, and by member functions and friends of d e r i v e d classes. See
section 15.7 for more information on f r i e n d s .

The level of data protection afforded by protected is generally more flexible


than that of the private level.

Data members and functions declared as protected are inherited by derived


classes. These derived classes hide the data from code outside of any instance
of the object.

One of the problems with using p r o t e c t e d data is that derived classes can
modify the base class data members directly (B a s e C l a s s : : D a t a M e m b e r ).
This means a derived class member functions does not have to use the get and
set member functions of the base class to modify protected data. A derived
class can then easily assign invalid values directly to protected data members.

Derived classes should depend solely on base-class services (base class public
member functions) and not on base class implementation. To achieve this we
should make data members private and provide public member functions to
manipulate this data.

Physics/ITLP 138 November 2013


C++ DPFE

Exercise 40 Base and Derived classes


 Examine the structure of base and derived classes
Task 1 Step 1
In eclipse, open the In eclipse, open the project Staff
project InheritanceStaf
f. Step 1
Examine the program to see Compile and run the program. The output should
how a derived class and be as shown in Figure 119.
base class are related. Note how the first five prompts ask for data that is
This program is used to common to all members of staff (N a m e , D O B ,
collect data on staff in a D O J , H o u s e N u m b e r and P o s t C o d e ).
business. The last two prompts ask for data that relates
All staff are part of a base specifically to management staff. The manager’s
class and have common t i t l e and n u m b e r o f s t a f f they are responsible
attributes. for.

The derived class is a


m a n a g e r class. There are
two data members that are
not shared with the base
class.
Learn how inheritance
relates to the reuse of
software.
In particular, how we create
new classes that use Figure 119

November 2013 139 OUCS


DPFE C++

existing class data and Step 2


behaviours. In the Project/Class Browser, see Figure 120, you
will see the main program file m a n a g e r M a i n . c p p
together with two . h (m a n a g e r . h and s t a f f . h )
files. These files detail the class’s public interface.
The files include function prototypes and data
members so the correct amount of memory can be
allocated at compilation time.

Figure 120
Also included are two source code implementation
files m a n a g e r . c p p and s t a f f . c p p that contain
the detail of how the member functions work.

Physics/ITLP 140 November 2013


C++ DPFE

Step 3
Open m a n a g e r . h . Examine the class definition
class Manager : public Staff.
The : colon character denotes inheritance. The
keyword p u b l i c is required. However, if we omit
p u b l i c the class definition will still compile.
M a n a g e r will still inherit from S t a f f but will
inherit privately. This means that only the member
functions of M a n a g e r get to call the member
functions of S t a f f .
Whenever you invoke a S t a f f method on a
M a n a g e r object elsewhere the compiler will give
an error. Objects that you create should be usable
to other classes and making them private is not
considered to be good practice.
The interface m a n a g e r . h has p u b l i c member
functions and p r o t e c t e d data members that can
be accessed via members of it’s own class or
member functions of a derived class.
Note the use of the constructor to initialise the data
members of the class, p o s i t i o n and n u m S t a f f .
The separate source code file m a n a g e r . c p p
contains the detail of the member function
implementation.
Note the use of the pre-processor directive
# i n c l u d e " s t a f f . h " at the top of the file. This is
needed as the class m a n a g e r inherits from s t a f f .
Without it the m a n a g e r class does not know about
the s t a f f class members
Step 4
Open the file m a n a g e r . c p p . The separate source
code file m a n a g e r . c p p contains the detail of the
member function implementation and how the
functions work.
Note the use of c o n s t after the member functions.
Constant member functions that never change a
class member value should be declared as c o n s t .
See Appendix 24.18 for more detail.

November 2013 141 OUCS


DPFE C++

Step 5
Open the file s t a f f . h . The interface s t a f f . h has
p u b l i c member functions and p r i v a t e data
members. Private data members can be accessed
via member functions of it’s own class or member
functions of the derived class m a n a g e r using base
class member functions.
Note the s e t member functions that are used by
the derived class to set the data members in the
base class.
There are also five c o n s t member functions to
return data from the base class object.
Step 6
Open the file s t a f f . c p p . The separate source code
file s t a f f . c p p contains the detail of the member
function implementation for the base class and
details how the functions work
Note the use of c o n s t after the member functions.
Again, constant member functions that never
change a class member value should be declared as
const.

Step 7
Open the file m a n a g e r M a i n . c p p . This is the
main file in which we create an instance of the
derived class manager called m a n 1 .
The user is prompted to enter the details for a
manager in the firm.
The number of staff the manager is responsible for
and their title are added to the instance data
members via the constructor.
All the other data is passed to the base class data
members via separate calls to the member
functions in the base class, ex.
Man1.setName(name);
The output is produced by calls to the instance
methods of the class, ex. M a n 1 . g e t N a m e ( ) ,
Man1.getnumStaff().
Note that these member functions are functions in
the base class s t a f f , not the derived class.

Physics/ITLP 142 November 2013


C++ DPFE

15.4. Member initialiser list


In all the classes we have created so far data members have been initialised in the
class constructor. Changes to data members have been made through member
functions and we have said that derived classes should depend solely on base-
class services (base class public member functions) and not on base class
implementation (to achieve this we make base class data members private).
It is also possible to initialise data members of derived classes and data members
of base classes by using a member initialisation list. Constant data members,
data members that are r e f e r e n c e s and member o b j e c t s must be initialised
using the i n i t i a l i s e r l i s t .
Figure 121 shows a typical derived class constructor initialising two derived class
data members and passing five other arguments to a base class constructor. Note
the : (colon) for the start of the initialiser list.
: p o s i t i o n ( p o s ) , n u m S t a f f ( n s ) , initialises the two derived class data
members.
S t a f f ( n a m e , D O B , D O J , h N u m , p C o d e ) passes five arguments to the base
class constructor.

Exercise 41 Using an initialiser list


 Modify a program to use an initialiser list
Task 1 Step 1
In eclipse, open the Open m a n a g e r . c p p and change the class
p r o j e c t S t a f f you used in constructor to match the constructor shown in
Exercise 40. Figure 121.
Two arguments, p o s and n s are being used in the
derived class with the other five being passed to the
base class constructor S t a f f ( n a m e , D O B , D O J ,
hNum, pCode).

Figure 121

Step 2
Change the class header file m a n a g e r . h to match
the constructor implementation. Seven arguments
are being passed to the derived class.

November 2013 143 OUCS


DPFE C++

Step 3
Modify the base class constructors S t a f f ( ) ; to
accept the five parameters being passed from the
base class initialiser list.

Step 4
Modify the statement M a n a g e r M a n 1 ( m a n T i t l e ,
n u m S t a f f ) ; in m a n a g e r M a i n ( ) used to create
and initialise the instance of M a n a g e r class.
When creating the instance of M a n 1 you will have
to pass all seven arguments.
Step 5
Remove the five statements from m a n a g e r M a i n ( )
that use base class member functions to initialise
the instance data members.
Compile and run the program. The output should
be the same as shown in Figure 119.

Physics/ITLP 144 November 2013


C++ DPFE

15.5. Preprocessor wrappper #indef


As we build larger programs other definitions and declarations will also be placed
in header files. Attempts to include a header file multiple times can occur in large
programs with many header files.
As some header files contain references to other . h files it is possible to attempt to
define a class more than once. This will lead to errors at compilation time.
To prevent this we use the preprocessor wrapper. The preprocessor wrapper
starts with # i f n d e f and ends with # e n d i f . The class definition for class S t a f f
shown below is enclosed in a preprocessor wrapper # i n d e f S T A F F _ H . i n d e f
means "if not defined". It prevents the code between # i f n d e f and # e n d i f from
being included in the compilation if what is inside the wrapper has already been
defined. If the header has not been included previously in a file then the header
file statements are included.
In the example shown (Figure 122) if the header s t a f f . h has not been included
previously in a file then the name S T A F F _ H is defined by the # d e f i n e directive
and the header file statements are included. If the header file has already been
included it is not included again.

Figure 122

Exercise 42 Add a preprocessor wrapper


 Add a preprocessor wrapper to the s t a f f . h header file

Task 1 Step 1
Add a preprocessor I n e c l i p s e , o p e n t h e p r o j e c t S t a f f file in the
directive to the s t a f f . h file I n h e r i t a n c e S t a f f folder.
in the project used in
Add a preprocessor wrapper to the s t a f f . h file.
Exercise 41.
Note: As there is only one derived class which uses
the staff class members it is not strictly necessary
to add a preprocessor wrapper to this class
definition. However, if we were to add another
derived class then there is the potential for the
header file to be included twice at compile time.

November 2013 145 OUCS


DPFE C++

Exercise 43 Adding an additional class


 Add an additional derived class

Task 1 Step 1
We need to add another Add two new files. You need to add a class
category of staff. Continue interface and a separate source code file (. c p p )
to use the program you that details the function implementation.
worked on in Exercise 42.
The administrator details you will need are the
The new category is building and office they work in.
Administrative staff.
Remember to use a member initialisation list.
A d m i n staff share all the
base class data members
attributes and can therefore
be treated as a derived class
of class s t a f f .
Modify the S t a f f project so
the program user can add a
new member of staff.
The user will be prompted
to add common staff details
and then to make a
selection as to the choice of
staff to add.
Figure 123 shows the sort of
interface needed.

Figure 123

Physics/ITLP 146 November 2013


C++ DPFE

15.6. Overriding base class methods


A derived class can declare a method to override a method in the base class. Note
that the method in the derived class must exactly match the method in the base
class in order to override it. The return type, name and num of arguments must
be the same. If the keyword c o n s t is used that must match as well.

Be aware that overriding base class methods can hide o v e r l o a d e d methods in


the base class. An overriding method in the derived class will hide all overloaded
methods with the same name in the base class. In below, both of the m o v e s ( )
methods in the base class are hidden even though they have different arguments.

Note that base class methods can be called, M y C a t . M a m m a l : : m o v e s ( ) , by


explicitly stating its class name, then the member function name separated by : : ,
the s c o p e o p e r a t o r . It can be useful to call base class methods in this way that
have been overridden by derived class methods.

Exercise 44 Overriding Base Class Methods


 Examine the program to understand how to override base class methods

Task 1 Step 1
In eclipse, open the Open O v e r R i d e B a s e C M project, compile and
project OverRideBaseC run the program. The output should be as shown
lassMeths. in Figure 124.
In eclipse, open the
project OverRideBaseC
l a s s M e t h s and examine
how classes in the base class
can be overridden.
Establish how overridden
base class member functions
can still be called from a
derived class.

November 2013 147 OUCS


DPFE C++

Figure 124

Step 2
The program has a base class M a m m a l and a
derived class C a t .
The base class has overloaded functions m o v e s ( )
and m o v e s ( 4 ) .
The derived class also has function m o v e s ( ) .
When an instance of C a t is created and the
function m o v e s ( ) called this overrides both of the
overloaded m o v e s ( ) functions in the base class.
There appears to be no way that a C a t object can
get access to the overloaded base class function
moves(int).

Step 3
In m a i n . c p p change the statement
M y C a t . m o v e s ( ) ; to M y C a t . m o v e s ( 4 ) ;
This would appear to a reasonable thing to do as
you want to pass an argument to a base class
member function and there is no matching
function in the derived class.
However, you will get a compilation error. An
overriding method in the derived class will hide all
overloaded methods with the same name in the
base class. Therefore m o v e s ( i n t ) is hidden to
any object of the derived class C a t .

Physics/ITLP 148 November 2013


C++ DPFE

Step 4
Examine the statement
M y C a t . M a m m a l : : m o v e s ( 4 ) ; Here we are
calling the base class function m o v e s ( 4 ) by
explicitly stating the instance, base class name
then member function separated by the : : s c o p e
operator.
We commonly call base class methods in this way
when they have been overridden by derived class
methods.

Exercise 45 Human Inheritance


 Create a new program that uses the class hierarchy shown in Figure 117

Task 1 Step 1
Create a new project, call it Create a new project, call it H u m P l a c M a m m a l
HumPlacMammal.
.
You will need to create
three . c p p class files and
then complete the detail Step 2
member function From the directory where you unpacked the
implementation. source materials, open the file called Hum
You will need one H u m a n , P l a c M a m m a l ( S t u d D e f i n i t i o n s ) . There are four
one P l a c e n t a l M a m m a l files you will need.
and a M a m m a l class. The Add all four files to the project you have just
class definitions have been created.
created for you.
Using the skeleton
framework in m a i n ( ) add Step 3
instance and member There are three . h header files showing the
functions calls for each of interfaces for the three classes shown in the
the three classes. hierarchy in Figure 117.
Many member functions Classes we are using are H u m a n , P l a c e n t a l
are overridden and you may M a m m a l and M a m m a l .
have to call base class The Human class is derived from Placental
member functions directly. Mammal and this derived from Mammal.
There is a framework for the m a i n function file.
This contains the main structure for the program.
No objects have been created and there are no
member function calls, this is for you to
implement.

November 2013 149 OUCS


DPFE C++

Figure 125

Step 4
Examine Figure 125. This shows how the program
should look when it is run.
An object of the H u m a n class is created and
functions in all three classes called to obtain the
output.
Some of the methods in the classes are overloaded
and some are overridden.
All the output in double quotes i.e. " w a l k e r e c t
o n t w o f e e t " has been returned from member
functions of one of the classes.

Step 5
Using the three interface files to guide you, create
three source code files (. c p p ) to implement
member function functionality.

Step 6
Using the m a i n function file create an instance of
the H u m a n class. Call the member functions of
this object to create an output similar to that
shown in Figure 125.
You will have to override some of the base class
methods and some base class methods you will
have to call directly.

Physics/ITLP 150 November 2013


C++ DPFE

15.7. Friends and Functions


A f r i e n d can be either another class or function. Being a f r i e n d allows access to
the data members and functions of a class from classes that are not derived
classes.
Normally, p r i v a t e and p r o t e c t e d members of a class cannot be accessed from
outside the same class in which they are declared. This rule does not affect
'friends'. Friends are functions or classes declared as ' f r i e n d s ' of the class.
To declare an external function as f r i e n d of a class, and allow the function to
have access to the private and protected members of this class, create a prototype
of the external function within the class. Precede the prototype with the keyword
friend.

Exercise 46 Examine a friend function


 Examine the program to understand how a friend function can access
private data members of a class.

Task 1 Step 1
In eclipse, open the Open F r i e n d s F u n c t i o n project, compile and run
project FriendsFunction the program. The output should be as shown in
. Figure 126.
Examine how a function can
be used to access private and
protected data members of a
class.

Figure 126

November 2013 151 OUCS


DPFE C++

Step 2
Open the file m a i n . c p p .
Before m a i n ( ) there is a function prototype.
Rectangle duplicate (Rectangle inrect);
The prototype name is duplicate, it accepts a
Rectangle object as an argument and returns a
Rectangle object.
Step 3
Examine the statement R e c t a n g l e r e c t ( 2 , 3 ) ;
Here we are creating an instance of R e c t a n g l e
class and initialising the data members width (2)
and height (3).
Beneath this a second Rectangle object is created
R e c t a n g l e r e c t b ; using the default constructor.
The next statement of interest is r e c t b =
d u p l i c a t e ( r e c t ) ; Here we are calling the
function duplicate and passing the object r e c t .
This object has data members w i d t h (2) and
h e i g h t (3).

Step 4
Examine the R e c t a n g l e function
Rectangle duplicate (Rectangle inrect)
{
Rectangle rect;
rect.width = inrect.width*2;
rect.height = inrect.height*2;
return (rect);
}
Inside the function a new R e c t a n g l e object is
created, Rectangle rect; The data members of
the object i n r e c t are accessed, doubled, then
assigned to the new object i n r e c t . This is unusual
as p r i v a t e and p r o t e c t e d members of a class
cannot normally be accessed from outside the
same class in which they are declared.

Physics/ITLP 152 November 2013


C++ DPFE

Step 5
Open r e c t a n g l e . h . Note that in the public
section of the class definition the function
d u p l i c a t e has been declared as friend of the
Rectangle class, f r i e n d R e c t a n g l e d u p l i c a t e
(Rectangle);
Declaring a prototype of the external function
within the Rectangle class, then preceding it with
the keyword f r i e n d , means the function can
access the private and public members of the
class.

Exercise 47 Add a friend function


 Add an additional class then use a friend function to access the private
data members.

Task 1
Modify the program in the
F r i e n d s F u n c t i o n project
by adding a new class
T r i a n g l e . Add a definition
and source file. The data
members are b a s e and
height.
Add a constructor,
destructor and member
functions to set the data
members and get the area.
Add another f r i e n d function
and prototype to m a i n ( ) .
Call the function t r i a n g l e .
The area of a triangle can be
calculated as half the base
multiplied by the height.
Add an additional function
prototype to the t r i a n g l e
header file.
Output the area of the new
t r i a n g l e object using the
f r i e n d function to access
the p r i v a t e data members
of the class.
Add an additional function
prototype to the t r i a n g l e
header file.

November 2013 153 OUCS


DPFE C++

Physics/ITLP 154 November 2013


C++ DPFE

15.8. Friends and Classes


In section 15.7 we have seen how to define a f r i e n d function. It is also possible to
define a c l a s s as f r i e n d of another c l a s s . The second class (the friend class) is
granted access to the protected and private members of the first class.

Exercise 48 Using friend classes


 Examine the program to understand how a friend class can access private
data members of another class.

Task 1 Step 1
In eclipse, open the Open m a i n . c p p and examine the statements
project FriendClass. shown in Figure 127.
Examine how to define a
class as friend of another
class.
The second class (the friend
class) can then be granted
access to the protected and
private members of the first
class. Figure 127
Here we are creating two instance objects, one
R e c t a n g l e and one S q u a r e .
Instance s q r uses the member function
s e t S i d e ( 4 ) to set the dimension of the square.
Instance r e c t calls the c o n v e r t member function
and passes the object s q r .

Step 2
Open s q u a r e . h . Examine the statement:
friend class Rectangle;
This statement declares class R e c t a n g l e as a
friend of S q u a r e . R e c t a n g l e can now access
private and protected data members of instances
of the S q u a r e class.
N o t e : Friendship is one way.
R e c t a n g l e is a friend of S q u a r e and has access
to private and protected data members of the
Square class, but Square objects do not have
access to private and protected data members of
the Rectangle class.
N o t e : Frienships are not transitive. You cannot
have a class as a friend of another friend class
unless explicitly specified.

November 2013 155 OUCS


DPFE C++

Also note in "r e c t a n g l e . h " that we use the pre-


processor directive, # i n c l u d e " s q u a r e . h " .
This header file is included as we make reference
to the class S q u a r e in the function 'c o n v e r t '.
Without the reference there is no way the compiler
can know about the class ' S q u a r e ' .

Step 3
Open r e c t a n g l e . c p p and examine the function
shown in Figure 128.

Figure 128
Function c o n v e r t is passed a parameter of type
Square (a).
In the statement width = a.side *2; a is the
o b j e c t and s i d e is the d a t a m e m b e r of the class
Square.
So the p r i v a t e data members (s i d e ) in class
S q u a r e have been accessed by public member
functions of the R e c t a n g l e class. These have
been assigned to the p r i v a t e data members of the
R e c t a n g l e class, w i d t h and h e i g h t .
When the R e c t a n g l e member function
r e c t . a r e a ( ) is called, the width and height of the
S q u a r e object are used to calculate the area of the
rectangle.

Step 4
Open r e c t a n g l e . h . Notice at the top of the file
the statement #include "square.h". This is
included as we make reference to the S q u a r e
class in the function c o n v e r t ( ) .
Comment out the # i n c l u d e directive and see
what happens when you re-compile.

Physics/ITLP 156 November 2013


C++ DPFE

Exercise 49 Adding a friend class


 Modify the program adding a third class. Make this class a friend of
Rectangle class.

Task 1 Step 1
Expand the program used in Create two new files, triangle.h and triangle.cpp.
Exercise 48.
Create a new class
Triangle.
Add a function definition
and source code file.
The class will have data
members w i d t h and h e i g h t
and a member function
g e t A r e a ( ) returning the
area of a triangle.
The area of the triangle can
be calculated as ½ the width
*height. The w i d t h and
h e i g h t are the p r i v a t e data
members of the R e c t a n g l e
class.
Do these calculations in a
function in T r i a n g l e that
can be called from m a i n ( ) .
Class T r i a n g l e will have to
be declared as a friend of
Rectangle.
The t r i a n g l e . h file will
need to make a pre-
processor reference to
Rectangle as Rectangle
objects are used in the class
definition.

November 2013 157 OUCS


DPFE C++

15.9. Composition
We have already seen that classes can be derived from other classes that provide
attributes and behaviours the new classes can use (i n h e r i t a n c e ). When we
include class objects as members of other classes we call it c o m p o s i t i o n or
aggregation.
A simple definition of composition is; defining a class as a member of another
class.
All normal scope rules then apply. Note however that a class that is a member of
another class does not enjoy the same benefits as a derived class, and only has
access to p u b l i c members of the containing class.
In previous exercises we have seen how to pass arguments to the constructor of a
class when an object is created.
In the following exercises we will pass r e f e r e n c e s to instance objects to a class
constructor and assign these objects to the data members of the class.
Whether we use inheritance or composition in our programs is much discussed.
Google “inheritance V composition”, and see what you get. It can make
interesting reading.
An objective view might be, use composition where you can unless inheritance
will really benefit the design of the program.

Exercise 50 Composition, using objects as members of other classes


 Examine the program to understand how we can use objects as data
members in other classes.

Task 1 Step 1
In eclipse, open the Compile and run the program. The program
project Composition. should look the same as Figure 129.
Examine the code to see how
D a t e class objects are used
as data members of the
E m p l o y e e class.

Figure 129

Physics/ITLP 158 November 2013


C++ DPFE

Step 2
Open m a i n . c p p and examine the statements
shown in Figure 130.

Figure 130
The first two statements create two D a t e objects
b i r t h and h i r e . Parameters are passed to the
class constructor to initialise the data members.
The third and fourth statements create two string
objects and initialise them.
The fifth statement creates an instance of class
E m p l o y e e called s t a f f and passes the employee
first and last names and the two D a t e class
objects to the class constructor.
The seventh statement calls the p r i n t method
using the s t a f f object.

Step 3
Open E m p l o y e e . h class definition. This is
shown in Figure 131.
The first statement is the class constructor.
Two s t r i n g s are being passed to the constructor
representing the first and last names.
C o n s t D a t e & is passing a reference to the D a t e
object for the DOB. The D a t e object is c o n s t and
cannot be changed and represents the birth date.
C o n s t D a t e & is repeated (for the date hired)
and the reference is passed to the data member for
hireDate.

November 2013 159 OUCS


DPFE C++

Figure 131

Step 4
Examine the two statements:
const Date &birthDate;
const Date &hireDate;
Both are constant references to data member
objects of the class D a t e .
Note the use of # i n c l u d e " D a t e . h " in the
E m p l o y e e class definition.
The E m p l o y e e class is using objects of the class
D a t e so must include the D a t e class definition.
Doing this means the compiler knows about the
D a t e class when the objects are passed via the
constructor in E m p l o y e e . c p p to the D a t e
constructor.
Step 5
Open E m p l o y e e . c p p . Examine Figure 132.
This shows the class constructor using a m e m b e r
i n i t i a l i s e r l i s t to pass initialiser reference values
to the D a t e member objects b i r t h D a t e and
h i r e D a t e in Employee class.
Each of the two object arguments has associated
data members, how do they get initialised?
Fortunately for us we do not have to get involved
in the technicalities of ensuring object data
members are initialised properly.
The compiler provides each class with a default
copy constructor that copies each member of the
constructors argument object into the
corresponding member of the object being
initialised.

Physics/ITLP 160 November 2013


C++ DPFE

N o t e : All data members can be initialised using a


member initialisation list.
However, c o n s t data members, data r e f e r e n c e
members and member o b j e c t s must be
initialised using a m e m b e r i n i t i a l i s a t i o n list as
we are here.

Figure 132

Step 6
Examine the code shown in Figure 133, the
h i r e D a t e . p r i n t ( ) ; statement.
The instance object h i r e D a t e is a reference to the
instance (h i r e ) passed from main to Employee.
The reference is used in the member initialiser list
(d a t e O f H i r e ) to initialise the member object
h i r e D a t e , hireDate(dateOfHire).
hireDate.print(); calls the D a t e member
function p r i n t ( ) of the instance h i r e of the D a t e
class.
The p r i n t ( ) function of the D a t e class object
outputs the date the employee was hired.
Ina similar way birthDate.print(); calls the
D a t e member function p r i n t ( ) of the instance
b i r t h of the D a t e class.

Figure 133

November 2013 161 OUCS


DPFE C++

Exercise 51 Composition, dates as object members of student class


 Create a program to track student enrolment

Task 1
Create a new project, call it
Students.
You need to maintain a
record of students on your
course.
Get the user to add records
for 3 new students. The
fields required are:
Name;
dateOfBirth;
dateOfEnrolment;
courseName;
Figure 134
Create instances of the class
S t u d e n t and store these in
a vector.
Use vector member
functions to add each
student object.
Use the Date class files from
Exercise 50 to store and
print dates.
The output should provide a
list of names with student
DOB, course name and the
date they enrolled on the
course, see Figure 135.

Figure 135

Physics/ITLP 162 November 2013


C++ DPFE

Exercise 52 Composition, Starting the OUCS ATM


 Create a user interface for the new ATM, soon be introduced at OUCS.

Task 1
Create a new project, call it
ATM Screen.
You will need to create three
classes, A T M , S c r e e n &
Keypad.
Figure 136 shows a class
diagram with composition of
classes.
A T M is using objects of class
S c r e e n and K e y p a d as
members. Class A T M has a
composition relationship
with class S c r e e n and
Keypad. Figure 136
A member function of the
S c r e e n class is used to
output prompts to screen
and a member function of
K e y p a d used to get user
input.
In the m a i n ( ) function
create an instance of the
ATM class.
The A T M class should
define a S c r e e n & K e y p a d
object as private members of Figure 137
the A T M class.
Use member functions of
S c r e e n class to output user
information. All input
should be via K e y p a d class
member functions.
Verify the account and PIN
numbers read in are valid
using member functions of
class A T M .
If they are not valid inform
the user, see Figure 137.
If they are valid provide a Figure 138
menu similar to that shown
in Figure 138 using S c r e e n
member functions.
The menu does not need to
have any functionality yet.

November 2013 163 OUCS


DPFE C++

16 Operator Overloading
One of the nice features of C++ is that you can give special meanings to
o p e r a t o r s when they are used with user defined classes. This is not something
you can do in all object oriented programming languages and notably this
functionality is not available in Java or C#.
The process of giving special meanings to operators is called o p e r a t o r
o v e r l o a d i n g . In C++ we implement overloading by providing special member-
functions on classes and these must follow a particular naming convention.
For example, to overload the addition operator + for your class you would provide
a member-function named operator+ for the class.
To overload the stream insertion operator < < for your class you would provide a
member-function named operator<< for the class.
All the operators we have used so far (and many more) can be overloaded and
there are very few that cannot be. The exceptions from those used so far are: ( . )
member selection and (: : ) scope resolution operators.
There are some important things to consider in operator overloading. Operator
overloading adds new functionality to existing operators. It is important that
comments explaining the new functionality of the overloaded operator are added
to your code. In the simple examples we use in this section it is relatively easy to
work out how the programs work. With more complex programs this will be
difficult.
Only use overloading when really necessary.

16.1. Overload + operator

Exercise 53 Overloading the addition operator +


 Exam the structure of a program to learn how to overload the + operator

Task 1 Step 1
In eclipse, open the Open m a i n C o m p l e x . c p p . Run the program and
project Operator see how it works.
Overloading plus.
Examine how to overload
the addition + operator.

Figure 139
Examine the code shown in Figure 147.
Here we are creating four objects of the C V e c t o r
class and initialising three of the first four objects.

Physics/ITLP 164 November 2013


C++ DPFE

Step 2

Figure 140
Examine the statement shown in Figure 140. At
first glance this seems to be using the addition
operator to add two instance objects and assigning
the result to d .
This is not possible and shows why operator
overloading can become confusing. The + operator
is overloaded and we will need to examine the class
implementation file in the next step to see how this
works.
Note that d = a ; the copy assignment operator is
the only operator member function implemented
by default. Object d becomes a copy object a .
Comment out the line shown in Figure 140 and add
d = a; in it’s place. Run the program and see
what happens.
When you have done this reinstate the statement
shown in Figure 140 and delete d = a;

Step 3
Open c o m p l e x . c p p .

Figure 141
Examine the function named o p e r a t o r + shown in
Figure 141.
o p e r a t o r + indicates the + addition operator is
being overloaded.

November 2013 165 OUCS


DPFE C++

Step 4
Examine the function o p e r a t o r + .
The function o p e r a t o r + shown in Figure 141 is
used to overload the + operator to add two complex
numbers.

As we have already seen, it is not possible to add


two complex number objects with the addition
operator. But by overloading the + operator we can
create a function that can add the real and
imaginary parts of each complex number and
return the result as a complex number.

The binary overloaded operator ‘+ ’ is used in the


statement d = a + b ; see Figure 140. In this
statement, the argument on the left side of the
operator ‘+ ’, a , is the instance object of the class
C V e c t o r in which the binary overloaded operator
‘+ ’ is a member function.

The right side of the operator ‘+ ’ is the instance


object b . This is passed as an argument to the
overloaded operator function ‘o p e r a t o r + ’ .
The object b is passed as an argument to the
operator ‘+ ’ inside the function ‘o p e r a t o r + ’ and
the real and imaginary elements are accessed as
p a r a m . x and p a r a m . y .
These values are added to a . x and a . y , which are
accessed directly as x and y . The return value is of
type class C V e c t o r .

The statement t h i s - > x + p a r a m . x ; uses the 't h i s '


pointer, passed (by the compiler) as an implicit
argument to each non-static member function.
Every object has access to its own address through
a pointer called 't h i s '. Static data members and
static member functions exist independently of any
objects of the class and so cannot have a 't h i s '
pointer.

Objects use the 't h i s ' pointer implicitly. So, in


CVector CVector::operator+ (CVector
p a r a m ) with no static data members, we can use
or omit the 't h i s ' pointer and the program would
compile the same.

Physics/ITLP 166 November 2013


C++ DPFE

Task 2
Modify the program to sum
the three C V e c t o r instance
object data members.
Compile and run the
program and explain what
is happening.

16.2. Overload stream operators

Exercise 54 Overloading stream insertion operators


 Exam the structure of a program to learn how to overload the stream
insertion and extraction operators

Task 1 Step 1
In eclipse, open the Open m a i n . c p p . Run the program and see how it
project Overload works. The output should be the same as Figure
Stream Insertion. 142.
Examine how to overload
the stream operators.

Figure 142

November 2013 167 OUCS


DPFE C++

Figure 143

Step 2
Examine the code shown in Figure 143. Two
objects of the class P a r t N u m b e r have been
created, p a r t and p a r t 2 .
The statement c i n > > p a r t is passing the i s t r e a m
object c i n and the instance object p a r t to the
overloaded function o p e r a t o r > > .
The statement c o u t < < p a r t is passing the
o s t r e a m object c o u t and the instance object p a r t
to the overloaded function o p e r a t o r < < .

The overloaded function o p e r a t o r < < returns an


o s t r e a m object with the data members of the p a r t
object concatenated.

Figure 144

Physics/ITLP 168 November 2013


C++ DPFE

Step 3
Open the implementation file S p a r e P a r t s . c p p
and examine the code shown in Figure 144.
The overloaded o p e r a t o r > > function returns a
reference to an i s t r e a m object and takes two
parameters by reference:
These are an i s t r e a m object and a user-defined
type.
The user-defined type 'P a r t N u m b e r ' is not passed
as a c o n s t parameter because the input operation
can modify it.
The body of the overloaded o p e r a t o r > > function
assigns members of the user-defined object to the
instance data members.

Figure 145

Step 4
Examine the code shown in Figure 145 of the
implementation file S p a r e P a r t s . c p p
The overloaded o p e r a t o r < < function returns a
reference to an o s t r e a m object and takes two
parameters by reference:
These are an o s t r e a m object and a user-defined
type.
The user-defined type 'p a r t N u m b e r ' is passed as a
c o n s t parameter because the output operation
doesn't modify it.
The body of the overloaded o p e r a t o r < < function
inserts members of the user-defined object into the
o s t r e a m object.

November 2013 169 OUCS


DPFE C++

Figure 146

Step 5
Open the definition file S p a r e P a r t s . h and
examine the code shown in Figure 146.
The two overloaded input and output operator
functions are declared as f r i e n d s because they
need to access non-public (private and protected)
class data members (M a n u f a c t u r e r etc) directly
as the class does not have any get member
functions.
The two overloaded functions are not part of the
class P a r t N u m b e r but added as prototypes of the
external functions within the class definition in
SpareParts.h.
See section 15.7 for more information on friend
functions.

Physics/ITLP 170 November 2013


C++ DPFE

17 Dynamic Memory Allocation


Until now we have allocated memory for objects and variables as we declared
them. The amount of memory was determined in the declarations section of the
source code, before the execution of the program.
But what happens if we need a variable amount of memory that can only be
determined during runtime? There are occasions when we need the user to
determine the amount of memory space.
Dynamic memory allocation enables memory to be allocated at runtime. In C++
we use the operators n e w and d e l e t e . The operator n e w is followed by a data
type specifier and [ ] if a sequence of more than one element is required. The
number of elements is enclosed within the square brackets [ 4 ] .
n e w returns a pointer to the beginning of the new block of memory allocated. It’s
form is:
type pointer;
int *number; declaring a pointer to an integer.
number = new int; this statement can be used anywhere in the program to
dynamically allocate memory (for 1 i n t ) as the program
runs.
delete number; This statement deletes the memory allocation.

pointer = new type [elements];


int * nums; declaring a pointer to an integer (n u m s ).
nums = new int [5]; Pointer n u m s now points to the first element in
memory block. This statement can be used anywhere
within the program to dynamically allocate memory (for
5 integers) as the program runs.
delete [] nums delete the array memory allocation.

Dynamically allocating Objects:


Cat *ptrCat; create a pointer to C a t object.

ptrCat = new Cat("Mr Business");


Allocate the memory for the C a t object. Call
the default constructor and return a pointer to the
object memory location.

delete ptrCat; This statement deletes the memory allocation.

November 2013 171 OUCS


DPFE C++

17.1. Dynamic Cats

Exercise 55 Dynamic memory allocation and pointers


 Exam the structure of a program to learn how to dynamically allocate
memory and then delete it.

Task 1 Step 1
In eclipse, open the Open I n h e r i t a n c e M a i n . c p p .
project Inheritance
Dynamic
Examine how to
dynamically allocate
memory for a C a t object.
Learn how to use pointers
and pointer notation to Figure 147
access member functions.
Examine the code shown in Figure 147.
Learn how to dynamically
The first statement creates a pointer p t r C a t that
allocate and delete
will point to a C a t object.
memory.
The second statement dynamically allocates the
memory for the Cat object. The default constructor
is called and the string argument passed. A pointer
to the object memory location is returned.

Step 2
Examine the two statements shown in Figure 148.

Figure 148
The first statement uses the pointer p t r C a t and the
arrow notation to point to the member function
s e t A g e ( ) . A parameter 5 is passed. This sets the
data member a g e in the base class to 5.
The second statement uses the pointer and arrow
notation to set the data member w e i g h t in the
base class.
Note how similar pointer notation is used to access
other member functions.

Step 3
Examine the statement delete ptrCat; This
statement frees the memory dynamically allocated
with n e w .

Physics/ITLP 172 November 2013


C++ DPFE

Exercise 56 Dynamic arrays


 Create a dynamic array and add additional objects.

Task 1 Step 1
Using the I n h e r i t a n c e Open I n h e r i t a n c e M a i n . c p p .
D y n a m i c project from
Add the code to create a dynamic array of cats.
Exercise 55 add a dynamic
array to add two additional Remember to take care when using pointers to loop
Cat objects. through the array or the address of the beginning
of the array may be lost.

Step 2
Output the names and other details of the new cats.
The output should be similar to that shown in
Figure 149.

Figure 149
Step 3
Remember to free the memory. See start of section
16.

November 2013 173 OUCS


DPFE C++

18 Pointer-Based string processing


18.1. Characters and Pointer-Based strings
In the previous sessions you have used the Standard Library s t r i n g class and
created s t r i n g objects.
Programs can also contain c h a r a c t e r c o n s t a n t s that can represent any key on
the keyboard, plus the machine’s character set. A c h a r a c t e r c o n s t a n t is the
integer value of the character, see appendix 24.19. Note the single quotation
marks (‘ a ’ , ‘ Z ’ ).
We have seen in earlier sessions that strings consist of a series of characters. We
can write s t r i n g l i t e r a l s or s t r i n g c o n s t a n t s in the following way, “J a n i n e
C a u l d e r ”, “0 1 8 6 5 2 8 2 8 2 8 ”. Note the double quotation marks.
Many C++ standard library functions only work with null-terminated ( ‘ \ n ’ )
pointer based strings and much legacy C++ code will use pointer based strings.
In C++ a pointer based string is an array of characters that must end in null
character ‘ \ 0 ’ . The null character marks where the string ends in memory. The
null character ‘ \ 0 ’ has the value 0 in the ASCII character set, see appendix 24.19.
char city[] = “Oxford”; O x f o r d is used to initialise a character array. The
array has 7 elements. The first six elements hold characters from the string
“Oxford” with the seventh holding null character ‘ \ 0 ’ .
const char * city_Ptr = “Oxford”; Using pointer c i t y _ P t r to point to the
letter ‘ O ’ in string literal “O x f o r d ”. The last character stored will be null
character ‘\ 0 ’. The location of the string in memory is not known, but the pointer
points to the address of the first character ‘ O ’ .
Both the declarations initialise variables to the string “Oxford”.
Strings can be read in to character arrays using the stream extraction c i n .
char city[7];
cin >> city;
Stores the string “Oxford” typed at the keyboard. Note the character array must
be big enough for the string and the null character ‘\ 0 ’ , in this case seven
elements.
A problem with using c i n is that a white space will terminate the reading process
and not all the characters will be stored. C++ provides the g e t l i n e ( ) function in
the < i o s t r e a m > header file to read a space (ASCII value 32) .
The statement cin.getline(city,7,‘\n’); uses the function. The three
arguments are the character array to store the string (c i t y ), the length of the
array (7 ) and any delimiting character (‘ \ n ’ ). The function will stop reading
characters when the number of characters read is one less than the array size, the
delimiter character (‘\n’) is met or EOF indicator is entered (Ctrl+z for
Windows, Ctrl+d for Linux). If the delimiter is met it is not stored.

Physics/ITLP 174 November 2013


C++ DPFE

18.2. String manipulation Functions


The C++ string handling library has many useful functions for manipulating
string data. There are functions for:
 Copying strings
 Comparing strings
 Searching for strings
 Searching for characters
 Establishing the length of strings
Some of the library functions can be seen in Appendix 24.17. To use these
functions you must include the header file <cstring> in any program using
them.

Exercise 57 Copying, concatenating and tokenising strings


 Examine a program to see how pointer based string manipulation
functions can be used.

Task 1 Step 1
In eclipse, open the Open the project s t r c a t S t r n c a t and run the
project strcatStrncat. program. Add your name when prompted. The
Examine the use of string output should be as shown in Figure 150.
manipulation functions

Figure 150

November 2013 175 OUCS


DPFE C++

Step 2
Examine the statements shown in Figure 151.

Figure 151
The first statement declaration creates an array, a
to hold 28 characters including the null character
‘\0’.
The next three statements create character arrays
to hold 25, 25 and 60 characters including null
characters.
char *Ptr; declares a pointer to a character. This
will be used to point to the start of one of the
arrays.

Step 3
The statement in Figure 152 uses the string
manipulation function g e t l i n e ( ) . g e t l i n e ( ) will
read into the array 25-1 characters.
The ending n u l l c h a r a c t e r is automatically
appended after the data stored in b.

Figure 152

Note this statement can also be written as :


cin.getline(b,24); as the function will only
read in a maximum of 25-1 characters whether or
not the delimiter ‘ \ n ’ is found.

Physics/ITLP 176 November 2013


C++ DPFE

Step 4
Examine the statement shown in Figure 153.

Figure 153
This function is similar to r e p l a c e ( ) in string
class. strcpy(c, b); copies the contents of array
b into array c including the null character.

Step 5
The statements shown in Figure 154 is similar to
s t r c p y ( ) but only copies a specified number of
characters, the first 3 characters of b into c.
Note that strncpy(c, b, 3); does not copy the
null character, this has to be done separately.
c[3] = '\0'; appends ' \ 0 ' to c's contents at
element number 4.

Figure 154
Step 6
Examine the statement shown in Figure 155.

Figure 155
P t r is a pointer to type char, declared at the start of
the program.
A pointer is assigned by s t r t o k to P t r and points to
the first character in the array a . s t r t o k then takes
the next delimiting character specified here as “ “
(space) and replaces it with null char ' \ n '
terminating the first token.
Here is the fancy bit. s t r t o k saves (s t a t i c v a r ) a
pointer to the next character following the token in
array a and returns a pointer to the current token.

November 2013 177 OUCS


DPFE C++

Step 7
Examine the code shown in Figure 156. The while
loop is used to continuously call s t r t o k .
Subsequent calls to s t r t o k have N U L L as the first
argument.
The N U L L argument indicates s t r t o k should
tokenise from the saved pointer location in array a .
When there are no tokens remaining s t r t o k
returns N U L L .
NOTE: s t r t o k modifies the input string replacing
each delimiter with the null char ' \ n ' . The original
string will be truncated to the first word in the
array.
To avoid losing the contents of the array, copy the
original string into another array before tokenising.

Figure 156

Task 2
Explain why the last
statement shown in Figure
150 shows the array
containing just the word
Welcome.

Physics/ITLP 178 November 2013


C++ DPFE

Exercise 58 Use string manipulation functions to modify a program


 Modify the program in Exercise 50 to use standard < c s t r i n g > library
functions to check the length of names input.

Task 1 Step 1
Copy your folder c o n s t c h a r * c o n s t , signifies a constant pointer to
C o m p o s i t i o n from constant data.
Exercise 50 and save it as
The class implementation file (. c p p ) should use
CompCString.
functions:
Modify the program to use
s t r l e n to get the length of the strings read and,
pointer based strings.
s t r n c p y to copy the characters read in to the two
The changes to the class
arrays, up to a maximum declared in the header
definition (. h ) file are
file. See Figure 157 for the character array sizes.
shown in Figure 157.

Figure 157

November 2013 179 OUCS


DPFE C++

Exercise 59 Using string manipulation functions


 Create a program to tokenise a paragraph of text. Establish how many
sentences, words and characters are used in the paragraph.

Task 1 Step 1
From the directory Using the program in Exercise 57 as a guide
where you unpacked initialise an array with the data in the Java.txt file.
the source materials,
open the file called Jav The program should allow the user to search for a
a.txt. user input word.
The text file contains a We also need to establish the following:
paragraph of text that we Number of characters in the complete paragraph.
need to analyse.
Number of characters (no spaces) in the paragraph.
Number of sentences in the paragraph.
The number of words each sentence contains.
You will need to tokenise the text using different
criteria.
The output should be similar to that shown in
Figure 158.

Figure 158

Physics/ITLP 180 November 2013


C++ DPFE

19 Polymorphism
In most of our programs so far we have been using inheritance where derived
classes inherit the data members of the base class. We have seen that a derived
class object is a kind of base class object.
One of the key features of a derived class is that a pointer to a derived class is
type-compatible with a pointer to its base class. Polymorphism is the art of taking
advantage of this simple powerful and versatile feature by using v i r t u a l functions
and b a s e class pointers
Polymorphism refers to an objects ability to respond in an individual manner to
the same message. With polymorphism one function can cause different actions
to occur depending on the type of object where the function is invoked.
Polymorphism occurs when a program invokes a v i r t u a l function through a
b a s e c l a s s p o i n t e r or r e f e r e n c e . C++ dynamically chooses the correct
function for the class from which the object was instantiated.
In C++ a virtual function is a member function of a b a s e class. Its functionality
can be over-ridden in its d e r i v e d classes and the whole function body replaced
with a new set of implementation in the d e r i v e d class.
Consider the class structure shown in Figure 159. Pigeon and Duck both inherit
from class Bird. Pigeon and Duck are derived classes.

Figure 159
There are features that are unique to Pigeons and features that are unique to
Ducks. These can be stored in data members of the class and accessed via the
member functions.
There are also features that are shared by the two classes. With a little
imagination we can consider two, both objects fly and walk. We will create two
member functions that are common to both classes, f l y ( ) and w a l k ().
With polymorphism one function can cause different actions to occur depending
on the type of object where the function is invoked. As we are going to refer to
members of the derived classes using a b a s e c l a s s p o i n t e r , we need all three
classes to have f l y and w a l k functions.
The secret to using polymorphism in C++ is to create a v i r t u a l member function
in the base class. Its functionality can be over-ridden in its derived classes using
functions with the same name as the virtual function. The whole function body is
replaced with a new set of implementation in the derived class.

November 2013 181 OUCS


DPFE C++

19.1. Polymorphism

Exercise 60 How polymorphism works


 Examine a program to establish how virtual functions and polymorphism
allow base class member functionality to be automatically overridden by
derived class functionality.

Task 1 Step 1
In eclipse, open the I n e c l i p s e , o p e n t h e p r o j e c t B i r d s . Compile
project Birds. and run the program.
Examine how a pointer to a The output should be the same as that shown in
base class is type- Figure 160.
compatible with a pointer
to a derived class. The output shows how by using a b a s e class
pointer and assigning a r e f e r e n c e to a derived
Understand how v i r t u a l class object it is possible to access the member
member functions used in a functions of the derived class.
b a s e class can have their
functionality over-ridden in It also shows how by using v i r t u a l functions and
the d e r i v e d classes. polymorphism it is possible for a virtual base class
member function to be over-ridden by any virtual
The whole function body in function in the derived classes with the same name.
the base class can be
replaced with a new set of As both derived classes have t a l k ( ) functions and
implementation in the t a l k ( ) is a v i r t u a l function in the base class then
derived class. the derived class t a l k ( ) functions will override the
base class function.

Figure 160

Physics/ITLP 182 November 2013


C++ DPFE

Step 2
Open m a i n . c p p . Examine the statements shown
in Figure 161.

Figure 161
Duck myDuck; creates an object of type D u c k
called m y D u c k .
The next statement creates a b a s e c l a s s pointer
P t r b of type B i r d . Assigned to the base class
pointer is a reference to a D u c k object, m y D u c k .
It is now possible to use polymorphism to invoke a
v i r t u a l function in a derived class through a base
class p o i n t e r or r e f e r e n c e .
C++ dynamically selects the correct virtual
function in the derived class using the r e f e r e n c e
object assigned to the b a s e class pointer.
The v i r t u a l function functionality in the base class
is over-ridden by that in the derived class and the
whole base class function body replaced with a new
set of implementation defined in the derived class.
Step 3
Open the base class definition b i r d . h . Examine
the statements shown in Figure 162.

Figure 162
The first statement is the class constructor.
The second statement is the class destructor.
Notice the class destructor is v i r t u a l . When the
base class destructor is declared as virtual, both
destructors (base and derived will be executed).
If virtual is omitted only the base destructor will be
executed.
A good rule of thumb is to include a destructor and
declare it as virtual if there are any virtual member
functions. This will ensure any destructors in
derived classes are executed.
The third statement defines a standard member
function w a l k ( ) .

November 2013 183 OUCS


DPFE C++

The last statement defines a v i r t u a l function


talk().
Declaring the function as v i r t u a l means its
functionality can be over-ridden by member
functions with the same name in its derived
classes.
The whole function in the base class is then
replaced with a new set of implementation in the
derived classes D u c k and P i g e o n .

Step 4
Open the base class implementation file b i r d . c p p .
Examine the code shown in Figure 163.
There is a class constructor, a destructor and two
member functions.
The base class functions are w a l k ( ) and the
v i r t u a l function t a l k ( ) .
The t a l k ( ) function in this base class will be
overridden by the t a l k ( ) functions in the derived
classes P i g e o n and D u c k with the same name.
The derived class function called is determined by
type of object (Duck or Pigeon) the base class
pointer is addressing.

Figure 163

Physics/ITLP 184 November 2013


C++ DPFE

Step 5
Open the D u c k class definition file d u c k . h .
Examine the code shown in Figure 164.

Figure 164
The first statement declares a function to override
the base class function talk().
N o t e : It is not strictly necessary to add v i r t u a l to
derived virtual methods but it is considered good
practice. Doing so makes it obvious what the
function does.
The second statement declares a method that could
override the base class function w a l k ( ) .
However, the function w a l k ( ) will not override the
base class function. With polymorphism a base
class pointer must be used to point to the derived
instance.
The base class pointer does reference a D u c k
object, but w a l k ( ) is not a virtual function
therefore the base class function w a l k ( ) will always
be called.
Only member functions that are v i r t u a l will be
overridden by the derived class function. Function
w a l k ( ) is not a virtual function so the pointer will
use the base class function w a l k ( ) .
Step 6
Open the Duck class implementation file
duck.cpp. Examine the code shown in Figure 165
The two functions are t a l k ( ) , the v i r t u a l function
that will override the base class function and
walk().
Derived class w a l k ( ) can not be called as the base
class pointer (P t r b ) used to access the member
functions cannot be used to access a non-virtual
member function.

November 2013 185 OUCS


DPFE C++

Figure 165

Step 7
Examine p i g e o n . h function definition and
p i g e o n . c p p the implementation file.
These derived class member functions work in a
similar way to the derived class D u c k described in
Exercise 60 Exercise 60Task 1.

Exercise 61 Accessing non-virtual member functions


 Modify the program to access the non-virtual member functions in the
derived classes.

Task 1
Using the project from the
previous exercise, Exercise
60 modify the program to
output the data contained
in the derived class member
functions w a l k ( ) .
There are two ways to do
this.
Firstly it is possible to make
the w a l k ( ) functions
v i r t u a l . Try this, ensuring
you can access the derived
class member functions and
get the expected output.
Secondly, and this is a good
bit trickier. Examine the
statements shown in Figure
161. Remember the pointer
is of type B i r d . This is a
base class pointer and by
using this base class pointer
and v i r t u a l functions we
can gain access to derived
member functions that are
also v i r t u a l .

Physics/ITLP 186 November 2013


C++ DPFE

This idea of using a base


class pointer is great for
polymorphism but prevents
us accessing non-virtual
member functions. What
other kind of pointer can be
used to access member
functions of the D u c k
class?

Exercise 62 Implement polymorphism


Modify a program to allow a base class pointer to access derived member
functions.

Task 1 Step 1
In eclipse, open the Run the program.
project Polygon.
The output should be as shown in Figure 166.
Modify the program.

Figure 166
Step 2
Modify the program so that the base class pointers
of type Polygon can be used to access all the
area() member functions of all class objects.
We do not want to access the objects directly
(object.method) as r e c t . a r e a ( ) and t r g l . a r e a ( ) .

November 2013 187 OUCS


DPFE C++

Member functions (virtual) should be accessed


with the following notation p o l y 1 - > a r e a ( ) ,
p o l y 2 - > a r e a ( ) where p o l y 1 and p o l y 2 are
pointers of type base class.
Make sure all class definitions are separate from
the class implementation files.
You will need to create new .cpp files for each
class.
Remember to include a pre-processor definition to
each of the class definition files to associate each.
Each derived class definition must be able to see
the base class Polygon so you will need to include a
pre-processor definition in each header file to the
base class as well.
Note the use of p r o t e c t e d data members w i d t h
and h e i g h t in class P o l y g o n . P r o t e c t e d data
members can be accessed by member functions of
its own class and by member functions of derived
classes.

Physics/ITLP 188 November 2013


C++ DPFE

20 Session 3
20.1. files used

Folders you will need. These are available from:


http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013/EclipseStudentFiles_part3.tgz
Algorithms and Predicates
Deques and Iterators
IO Basic IN_OUT
Lists and Iterators
Multimap Container
Multiset Container
PureVirtualFunctions
Vectors and Iterators

November 2013 189 OUCS


DPFE C++

21 Abstract Classes
All the programs we have created so far have been made up of classes. From
these classes we have created objects of the class. There are occasions when it is
useful to create classes from which we never intend to create instance objects.
These are a b s t r a c t classes.
A b s t r a c t classes are usually used as b a s e classes. Abstract classes can never be
instantiated and require the derived classes to complete the class before
instantiation.
If there is an a b s t r a c t class then there is a good chance there is also a c o n c r e t e
class. This is the name given to the classes you have created so far; classes that
can be instantiated are called concrete classes.
We can create an a b s t r a c t class S h a p e and then derive concrete classes with
the specific detail necessary to instantiate an object. The concrete classes might
be C i r c l e , S q u a r e and T r i a n g l e . Figure 167 shows a primitive inheritance
hierarchy for shapes.

Figure 167
In Figure 167 we can define S h a p e as an a b s t r a c t class. It would be extremely
difficult to define the data members and member functions for a s h a p e class.
How do you draw a shape? What kind of shape? What attributes does the shape
have?
These are reasonable questions but questions that we cannot answer without
more detail. To help answer the question we make the class abstract and then
add the specifics in the concrete classes C i r c l e , R e c t a n g l e and T r i a n g l e .
To create an abstract function we need to make one of its v i r t u a l functions a
p u r e v i r t u a l function by placing “= 0 ” in the declaration. This is known as the
pure specifier.
virtual void area() const = 0;
When we use abstract classes the concrete derived classes must override all base
class virtual functions with concrete implementations of the abstract class
functions.
So what is the difference between a virtual function and a pure virtual function?
A virtual function has implementation in the function and the derived class has
the option of overriding the function.
A pure virtual function provides no implementation and needs the derived class
to override it with any implementation. An abstract class cannot be instantiated
and simply declares common attributes and behaviours.

Physics/ITLP 190 November 2013


C++ DPFE

21.1. Examining an Abstract Class

Exercise 63 Abstract classes & dynamic binding


 Examine a program to establish how abstract classes work.
 Look at dynamic binding.

Task 1 Step 1
In eclipse, open the In eclipse, open the project PureVirtual.
project PureVirtualFun Compile and run the program. The output should
ctions. be the same as that shown in Figure 168.
Examine the program to This program allows us to create two members of
establish how to create an staff. Salaried and Hourly paid. There is a base
a b s t r a c t class. class Employee and two derived classes Salaried
Understand how to create a and Hourly.
p u r e v i r t u a l function and The output for each of the two instance objects
understand the difference appears twice to demonstrate the use of s t a t i c and
between a v i r t u a l function d y n a m i c binding.
and p u r e v i r t u a l function.
You will also be introduced
to s t a t i c and d y n a m i c
binding.

Figure 168

November 2013 191 OUCS


DPFE C++

Step 2
Open m a i n . c p p . Examine the statements shown
in Figure 169.

Figure 169
This is a function prototype receiving a constant
pointer to a constant object, base class o b j e c t
Employee.
This is the prototype for the function used to call
the derived class functions using polymorphism
and dynamic binding.

Step 3
Examine the statements shown in Figure 170. The
first statement creates an instance s E m p l o y e e of
class S a l a r i e d and initialises the data members
via the constructor.
The second statement creates an instance
h E m p l o y e e of class H o u r l y and initialises the
data members via the constructor.

Figure 170

Step 4
Examine the statements shown in Figure 171. The
statement s E m p l o y e e . p r i n t ( ) is using the dot
member-selection operator “object.method()”.
This means the compiler can identify (knows
about) each object (s E m p l o y e e and h E m p l o y e e )
at compile time and knows which p r i n t and
e a r n i n g s functions to call. This is s t a t i c
binding.

Figure 171

Physics/ITLP 192 November 2013


C++ DPFE

Step 5
Examine the statements shown in Figure 172.

Figure 172
In this statement we create a vector to hold
p o i n t e r s of type E m p l o y e e class. The vector has
an initial size of two elements.

Step 6
Examine the statements shown in Figure 173.

Figure 173
Here the vector is initialised with addresses of
S a l a r i e d Employees and H o u r l y paid Employees.
The addresses are stored in base class E m p l o y e e
pointers.
This is possible as a pointer to a derived class is
type-compatible with a pointer to its base class.
This is polymorphism.

Step 7
Examine the statements shown in Figure 174. The
f o r loop lets us loop through the vector elements
and pass the address of each object to the function
virtualPointer.

Figure 174

November 2013 193 OUCS


DPFE C++

Step 8
Examine the statements shown in Figure 175.
Both statements are used to access virtual
functions.
The first statement calls the p r i n t ( ) function using
the base class (E m p l o y e e ) pointer and the arrow
notation (- > ). This calls the derived class p r i n t ( )
function.

The derived class member function then calls the


base class p r i n t ( ) function to access base class data
members F i r s t n a m e , L a s t N a m e and N I
number.
The second statement accesses the derived class
function of the base class pure virtual function
earnings().
Again the b a s e C l a s s P t r is used to access the
derived class function p r i n t ( ) .
Function v i r t u a l P o i n t e r does not have any
information on the derived classes. It is just being
passed pointer information about the base class
E m p l o y e e . Because of this there is no way the
compiler can know which concrete classes to call
via the base class pointer at compile time.
At execution time, using polymorphism, each
virtual function call calls the function on the object
to which the pointer b a s e C l a s s P t r (Employee)
points at that time. This is d y n a m i c b i n d i n g .

Figure 175

Physics/ITLP 194 November 2013


C++ DPFE

Exercise 64 Create a new Abstract class


 Create a new abstract class Shape with three derived classes.

Task 1 Step 1
Create a new project, call it Using the hierarchy shown in Figure 167 create an
Shapes. abstract class S h a p e with no implementation.
Step 2
Create three derived classes, P a r a l l e l o g r a m ,
R e c t a n g l e and T r i a n g l e . You will need two data
members for each object, width (base) and height.
Set these using class constructors when the objects
are created.
Step 3
Output the area of each object using polymorphism
and dynamic binding.

November 2013 195 OUCS


DPFE C++

Exercise 65 ATM, base class pointers and private utility functions


 Create a new abstract class Shape with three derived classes.

Task 1 Step 1
In eclipse, open the Open A T M . c p p .
project Student ATM
Abstract Balance Examine the statement:
Inquiry Transaction * transactionPtr;
This statement creates a b a s e class pointer
(t r a n s a c t i o n P t r ) to the T r a n s a c t i o n class.
Transaction is an a b s t r a c t class and a class that
we will never instantiate any objects from.
The class is used to declare the common attributes
and behaviours for its derived classes
B a l a n c e I n q u i r y , D e p o s i t and W i t h d r a w a l .
See Figure 176.
Note the common behaviour for the derived classes
is r u n ( ) .

Figure 176

Physics/ITLP 196 November 2013


C++ DPFE

Step 2
Examine the statement:
transactionPtr =
createTransaction(selection);
c r e a t e T r a n s a c t i o n ( ) is a p r i v a t e u t i l i t y
f u n c t i o n and can only be accessed from within the
class.
s e l e c t i o n is the user input choice from the menu
(1-4). c r e a t e T r a n s a c t i o n returns a pointer of
type determined by the user input (1-4).

Figure 177

November 2013 197 OUCS


DPFE C++

Step 3
Examine the c r e a t e T r a n s a c t i o n ( ) function
shown in Figure 177.
The function receives an integer (user input) that
corresponds to the action the user wants to take,
B a l a n c e I n q u i r y , W i t h d r a w a l or D e p o s i t .
Case select option 3 (D e p o s i t ) is not functional
just yet so there is a prompt to let the user know.
If the user inputs a 1 , a B a l a n c e I n q u i r y object is
dynamically created and assigned to a base class
pointer t e m p P t r .
Similarly if the user inputs a 2 , a W i t h d r a w a l
object is dynamically created and assigned to the
base class pointer t e m p P t r .
The base class pointer is returned to the calling
function and assigned to another base class
pointer, see Figure 178.

Figure 178

Step 4
Examine the statement shown in Figure 179.

Figure 179

The t r a n s a c t i o n P t r pointer is a base class pointer


and can point to any of the three derived class
objects.
If we assume the user entered a 1 for a balance
inquiry then because our b a s e class pointer is type
compatible with all three pointer types, it now
points to an object of type B a l a n c e I n q u i r y .
The statement shown in Figure 179 therefore
invokes the v i r t u a l function in B a l a n c e I n q u i r y
to get the user balance.

Physics/ITLP 198 November 2013


C++ DPFE

Task 2
Create a new class D e p o s i t
and add the necessary
functionality to present the
user with sufficient
information to let them
know they have called the
relevant functions in the
Deposit class.
Inform the user from
within the class that you
will be continuing to
develop the O U C S A T M .

November 2013 199 OUCS


DPFE C++

22 Completing the OUCS ATM

Exercise 66 OUCS ATM class diagram


 Add additional classes to the ATM.

Task 1
Using the class diagram
shown in Figure 181 create
additional classes to
provide more functionality
to the OUCS ATM.
Add functionality to check
balance, make withdrawals
and deposits.
The interface should be
similar to Figure 180.

Figure 180

Physics/ITLP 200 November 2013


C++ DPFE

Figure 181 Class diagram of OUCS ATM

November 2008 201 OUCS


DPFE C++

23 The Standard Template Library


The standard Template Library (STL) defines many common data structures and
algorithms to process these structures.
Some of the structures we have already worked with, vectors and lists. As we
have seen it is possible to store objects of any data type in these structures.

23.1. Containers
Vector, deque and list are three STL containers. They are more correctly called
f i r s t - c l a s s c o n t a i n e r s . Other containers are called a d a p t e r s and n e a r
c o n t a i n e r s . Pointer based arrays, string, bitsets and valarrays are near
containers, we will not be looking at those in this session.

C o n t a i n e r s in the STL fall into two categories, s e q u e n c e containers see


Table 8, and a s s o c i a t i v e containers see Table 9.

sequence containers
vector
lists
deque
Table 8

Sequence containers are ordered collections in which every element has a


certain position. Ordered does not mean the elements are sorted ascending or
descending, but refers to the position at the time and place of the insertion.

associative containers
set
multiset
map
multimap
Table 9

Associative containers are sorted collections in which the actual position of an


element depends on its value due to a certain sorting criterion.
Using associative containers, if you put ten elements into a collection, their order
will depend only on their value. The order of insertion doesn't matter.
Sequence and associative containers are collectively known as first-class
containers.

23.1.1 Why different containers?


It is to do with how efficiently each type grows or reduces in size when elements
are added or removed.
Insertion at the back of a vector is efficient as the vector simply grows to
accommodate the new item if there is not already sufficient space.

OUCS 202 November 2008


C++ DPFE

It is not efficient to insert or delete elements in the middle of the vector as the
entire vector must be moved as vector elements must occupy contiguous cells in
memory.
It is possible to insert elements anywhere in a vector but other containers are
better suited to this, notably the deque and list.
If we need to add or delete data from both ends of a container the deque would be
a good choice.
Again both containers (deque and list and even the vector) can do the job but the
deque is more efficient with insertions and deletions from the front.
If we need to make insertions and deletions at the start, or end or anywhere else
in the container then the list would be most efficient.

23.2. Common member functions for all containers

Common member functions for all


containers
Type obj Allows initialization through default constructor
Type newobj(srcobj) Copies constructor, Type(object) = object
Creates container and copies elements from beg
Type newobj(beg, end) to end
obj.size( ) Returns the number of elements in object
obj.empty( ) Returns a bool stating whether container is empty
Returns the maximum number of elements
obj.max_size( ) possible
obj1 == obj2 Checks all elements in containers for equality
obj1 != obj2 Equivalent to !(obj1 == obj2)
obj1 < obj2 Checks all elements in containers for predicate *
obj1 > obj2 Checks all elements in containers for predicate *
obj1 <= obj2 Checks all elements in containers for predicate *
obj1 >= obj2 Checks all elements in containers for predicate *
obj1 = obj2 Assigns one container to another
obj1.swap(obj2) Swaps the data in containers obj1 with obj2
swap(obj1, obj2) Swaps the data in containers obj1 with obj2
obj.begin( ) Returns the iterator for the first element
obj.end( ) Returns the iterator for the last element + 1
obj.erase( ) Erases one or more elements from container
obj.clear( ) Erases all elements from container
obj.insert(position,element) Inserts a copy of element.
Table 10

* A predicate is an expression that returns either true or false.

All STL containers provide similar functionality and as we would expect, each
container has associated member functions. A subset of these member functions
is common to all containers i.e. s i z e ( ) .
s i z e ( ) member function will return the number of elements of any container
type it is used with.

November 2008 203 OUCS


DPFE C++

23.3. Algorithms
The STL provides many standard algorithms that can be used generically across a
variety of containers.
The header < a l g o r i t h m > defines a collection of functions especially designed to
be used on ranges of elements.
Algorithms are global functions that operate with iterators. Often one algorithm
can operate on elements of different container types. It is also possible to use
algorithms for user-defined container types and arrays.
These algorithms offer general fundamental services, such as searching, sorting,
copying, reordering, modifying, and numeric processing. Understanding what
algorithms can be used with which containers takes time to learn.
However, learning the algorithms you can use with selected containers will save
time in the long run as there is no need for you to develop your own algorithms
with so many reusable ones available, see Table 11.

C++ Algorithms
accumulate sum up a range of elements
adjacent_difference compute the differences between adjacent elements in
a range
adjacent_find finds two items adjacent to each other
binary_search determine if an element exists in a certain range
copy copy some range of elements to a new location
copy_backward copy a range of elements in backwards order
count return the number of elements matching a given value
count_if return the number of elements for which a predicate is
true
equal determine if two sets of elements are the same
equal_range search for a range of elements that are all equal to a
certain element
fill assign a range of elements a certain value
fill_n assign a value to some number of elements
find find a value in a given range
find_end find the last sequence of elements in a certain range
find_first_of search for any one of a set of elements
find_if find the first element for which a certain predicate is
true
for_each apply a function to a range of elements
generate saves the result of a function in a range
generate_n saves the result of N applications of a function
includes returns true if one set is a subset of another
inner_product compute the inner product of two ranges of elements

OUCS 204 November 2008


C++ DPFE

C++ Algorithms

inplace_merge merge two ordered ranges in-place


is_heap returns true if a given range is a heap
is_sorted returns true if a range is sorted in ascending order
iter_swap swaps the elements pointed to by two iterators
lexicographical_compare returns true if one range is lexicographically less than
another
lower_bound search for the first place that a value can be inserted
while preserving order
make_heap creates a heap out of a range of elements
max returns the larger of two elements
max_element returns the largest element in a range
merge merge two sorted ranges
min returns the smaller of two elements
min_element returns the smallest element in a range
mismatch finds the first position where two ranges differ
next_permutation generates the next greater lexicographic permutation of
a range of elements
nth_element put one element in its sorted location and make sure
that no elements to its left are greater than any
elements to its right
partial_sort sort the first N elements of a range
partial_sort_copy copy and partially sort a range of elements
partial_sum compute the partial sum of a range of elements
partition divide a range of elements into two groups
pop_heap remove the largest element from a heap
prev_permutation generates the next smaller lexicographic permutation
of a range of elements
push_heap add an element to a heap
random_shuffle randomly re-order elements in some range
remove remove elements equal to certain value
remove_copy copy a range of elements omitting those that match a
certian value
remove_copy_if create a copy of a range of elements, omitting any for
which a predicate is true
remove_if remove all elements for which a predicate is true
replace replace every occurrence of some value in a range with
another value
replace_copy copy a range, replacing certain elements with new ones

November 2008 205 OUCS


DPFE C++

C++ Algorithms
replace_copy_if copy a range of elements, replacing those for which a
predicate is true
replace_if change the values of elements for which a predicate is
true
reverse reverse elements in some range
reverse_copy create a copy of a range that is reversed
rotate move the elements in some range to the left by some
amount
rotate_copy copy and rotate a range of elements
search search for a range of elements
search_n search for N consecutive copies of an element in some
range
set_difference computes the difference between two sets
set_intersection computes the intersection of two sets
set_symmetric_difference computes the symmetric difference between two sets
set_union computes the union of two sets
sort sort a range into ascending order
sort_heap turns a heap into a sorted range of elements
stable_partition divide elements into two groups while preserving their
relative order
stable_sort sort a range of elements while preserving order
between equal elements
swap swap the values of two objects
swap_ranges swaps two ranges of elements
transform applies a function to a range of elements
unique remove consecutive duplicate elements in a range
unique_copy create a copy of some range of elements that contains
no consecutive duplicates
upper_bound searches for the last possible location to insert an
element into an ordered range

Table 11

23.4. Introduction to iterators


STL i t e r a t o r s (similar to pointers) are used to manipulate individual container
elements in the same way pointers are used to address and manipulate elements
in arrays. It is also possible to manipulate standard arrays as if they were
containers by using STL algorithms and standard pointers as iterators.
It is important to know that each first-class container supports specific iterator
types. The type of iterator determines which algorithms can be used with the
container.

OUCS 206 November 2008


C++ DPFE

Certain iterator operations are uniform across all containers. The dereferencing
operator (* ) dereferences an iterator so that you can use the element to which it
points in a similar way to working with pointers.
The + + operation on an iterator moves it to the next element of the container in a
similar way to incrementing a pointer to an array moves the pointer to the next
element.
All STL first-class containers have member functions b e g i n ( ) and e n d ( ) .
b e g i n ( ) returns an iterator pointing to the first element in the container and
e n d ( ) returns an iterator pointing to the first element past the end of the
container.
If we assume an iterator “i t r ” points to the first element of a container, + + i t r
points to the second element and * i t r refers to the element pointed at by i t r .
Note that the iterator resulting from e n d ( ) can only be used in an equality or
inequality comparison to determine whether the iterator “i t r ” has reached the
end of the container. This is because the member function e n d ( ) returns an
iterator that refers to a position past the last element in a container and not the
last element of the container.

Iterator Types
input Used to read an element from a container.
An input operator can only move in a
forward direction (container beginning to
end) one element at a time. Input iterators
support only one-pass algorithms – the
same operator cannot be used to pass
through a sequence twice.
output Used to write an element to a container. An
output iterator can move only in the
forward direction one element at a time.
Output iterators support only one-pass
algorithms – the same output iterator
cannot be used to pass through a sequence
twice.
forward Combines the capabilities of input and
output iterators and retains their position
in the container.
bidirectional Combines the capabilities of a forward
iterator with the ability to move in the
backward direction (from end towards the
beginning). Bidirectional iterators support
multipass algorithms.
random access Combines the capabilities of a bidirectional
iterator with the ability to directly access
any element of the container, to jump
forward or backward by an arbitrary
number of elements.

Table 12

Containers that support random access iterators can use all algorithms in the
STL.

November 2008 207 OUCS


DPFE C++

There is an iterator category hierarchy with each category providing a specific set
of functionality. Figure 182 shows the hierarchy. Each iterator category supports
all the functionality of the categories above it.
The bottom category, r a n d o m a c c e s s iterators are the most powerful iterators
having their own functionality together with the functionality of all the categories
above.
As we have mentioned the iterator category that each container supports (see
Table 13) determines whether that container can be used with specific algorithms
in the STL.

Figure 182

Table 13 show the iterator types supported by different containers.

Sequence containers (first class) Iterator category


vector random access
deque random access
list bidirectional
Associative containers (first class)
set bidirectional
multiset bidirectional
map bidirectional
multimap bidirectional

Table 13

Iterator operation
All iterators

++p preincrement an iterator


p++ postincrement an iterator

OUCS 208 November 2008


C++ DPFE

Iterator operation
Input iterators

*p dereference an iterator
p = p1 assign one operator to another
p == p1 compare iterators for equality
p != p1 compare iterators for inequality
Output iterators

*p dereference an iterator
p = p1 assign one operator to another
Forward iterators forward iterators contain all the functionality of
both input iterators and output iterators
Bidirectional iterators

--p pre-decrement an iterator


p-- post-decrement an iterator
Random access iterators

p += i increment the iterator p by i positions


p -= i decrement the iterator p by i positions
p+i Expression value is an iterator positioned at p
and incremented by i positions
p-i Expression value is an iterator positioned at p
and decremented by i positions
p [i] Return a reference to the element offset from p
by i positions
p < p1 Return true if iterator p is less than iterator p1
otherwise return false. (i.e. iterator p is before
p1 in the container).
p <= p1 Return true if iterator p is less than or equal to
iterator p1 otherwise return false. (i.e. iterator p
is before p1 or at the same location as iterator p1
in the container).
p > p1 Return true if iterator p is greater than iterator
p1 otherwise return false. (i.e. iterator p is after
p1 in the container).
p >= p1 Return true if iterator p is greater than or equal
to iterator p1 otherwise return false. (i.e.
iterator p is after p1 or at the same location as
iterator p1 in the container).

Table 14

Algorithms act indirectly on the containers by using i t e r a t o r s and many


algorithms act on s e q u e n c e s of elements defined by p a i r s of i t e r a t o r s .
When using pairs of iterators the first algorithm iterator will point to the first
element of the sequence and the second pointing to one element past the last
element.

November 2008 209 OUCS


DPFE C++

In the example below the s o r t ( ) algorithm is using two iterators pointing to the
start and end of the vector called m y V e c t o r ;
sort (myVector.begin(),myVector.end();
Because s o r t ( ) algorithm uses random-access iterators to the initial and final
positions of the sequence to be sorted, s o r t ( ) can be used with the v e c t o r and
d e q u e containers but not the l i s t container. Lists only support bidirectional
iterators.
However, l i s t containers have a member function s o r t ( ) that can be used to sort
list elements.
Table 13 shows the different iterators supported by each container.
Table 15 shows predefined iterator t y p e d e f s found in the class definitions of the
STL containers.

Predefined typedefs for iterator


Direction of ++ Capability
types
iterator forward read/write
const_iterator forward read
reverse_iterator backward read/write
const_reverse_iterator backward read
Table 15

23.5. Member Functions by Container

Table 16 and Table 17 below show the member functions and algorithms available
to each container, v e c t o r , l i s t and d e q u e .

The STL algorithms can also be decoupled from the STL container classes. What
this means to us is that certain algorithms (r e v e r s e is a good example) can be
used to reverse elements in a vector, a list and deque. They can even be used to
reverse elements in C type arrays.

It is worth noting that the l i s t container class also has a m e m b e r f u n c t i o n


called r e v e r s e .

If we had created a l i s t in our program called a d d r e s s e s it could be reversed in


one of two ways.

Using the member function: addresses.reverse();

or by using the STL algorithm:

reverse(addresses.begin(),addresses.end());

The reason we can use the r e v e r s e algorithm with the l i s t container is because
r e v e r s e uses bidirectional iterators supported by the l i s t container.

OUCS 210 November 2008


C++ DPFE

Vector Member Functions List Member Functions


vector::assign vector::max_size list::assign list::pop_front
vector::at vector::operator = list::back list::push_back
vector::back vector::operator [ ] list::begin list::push_front
vector::begin vector::pop_back list::clear list::rbegin
vector::capacity vector::push_back list::empty list::remove
vector::clear vector::rbegin list::end list::remove_if
vector::empty vector::rend list::erase list::rend
vector::end vector::reserve list::front list::resize
vector::erase vector::resize list::get_allocator list::reverse
vector::front vector::size list::insert list::size
vector::get_allocator vector::swap list::max_size list::sort
vector::insert list::merge list::splice
list::operator = list::swap
list::pop_back list::unique

Table 16

Deque Member Functions


deque::assign deque::operator =
deque::at deque::operator [ ]
deque::back deque::pop_back
deque::begin deque::pop_front
deque::clear deque::push_back
deque::empty deque::push_front
deque::end deque::rbegin
deque::erase deque::rend
deque::front deque::resize
deque::get_allocato
r deque::size
deque::insert deque::swap
deque::max_size
Table 17

23.6. Reading and writing files

Learning to read and write data to file is something that must be learned to make
meaningful use of containers.

Adding data to containers can be a time consuming and tedious process, using
files relieves the boredom of manually adding data before we manipulate our
containers using algorithms and iterators.

In the examples used in the following exercises data is sent to/from file in simple
text format and can easily be read with a text editor. It is also possible to output
and input data in binary format.

C++ imposes no structure on the files we create and with our simple examples of
storing integers, doubles etc this will not be a problem. If we need to store objects

November 2008 211 OUCS


DPFE C++

(with several different data members) we will need to structure the file
accordingly. This will be shown in later exercises.

To write to a file we need to add the < f s t r e a m > header file. This allows the use
of o f s t r e a m class instance objects to write data to file as output streams.

The file to be associated with the stream can be specified either as a parameter in
the constructor ofstream outFile( "Numbers.txt", ios::out);when the
instance object o u t F i l e is created.

or by calling member function o p e n .

ofstream outFile;
outFile.open("Numbers.txt", ofstream::out );

i o s : : o u t and o f s t r e a m : : o u t are modes the file will be opened in. In the above
cases o u t denotes writing to file with any existing data in the file being deleted.
Mode i o s : : a p p appends data to the file.

When data has been transferred to file the interface can be closed (or
disassociated) by calling member function c l o s e , outFile.close(); Once
closed, the same file stream object can be used to open another file.

To read from a file the i f s t r e a m class instance objects allow us to read data from
files as input streams.

The file to be associated with the stream can be specified either as a parameter in
the constructor ifstream inFile( "Numbers.txt", ios::in ); in a similar
way as when writing to file.

or by calling member o p e n .

ifstream inFile;
inFile.open("Numbers.txt", ofstream::in );

After all data has been transferred the interface can be closed (or disassociated)
by calling member c l o s e . Once closed, the same file stream object may be used
to open another file.

The member function i s _ o p e n can be used to determine whether the stream


object is currently associated with a file.
The following program shows how to add each element of an array of integers to
file. The program then reads each record from file into another vector and the
contents output to screen

OUCS 212 November 2008


C++ DPFE

Exercise 67 Using files to add data to containers


 Open an existing program and examine the code
 Modify the program to append data to file

Task 1 Exercise 68
In eclipse, open Open F i l e I O project and examine the code. Only
the project FileIO the parts that relate to writing to and reading from file
in the I O B a s i c are covered here.
I N _ O U T folder and
examine the code to The < f s t r e a m > header file is included to allow the use
establish how to read of o f s t r e a m and i f s t r e a m classes to create instance
and write files. objects to read and write to and from file.

Exercise 69
ofstream outFile("Numbers.txt", ios::out );
The statement above creates an instance of o f s t r e a m
called o u t F i l e . The ofstream constructor takes two
arguments, the name of the file and how the file should
be opened.
In this example o u t indicates any data in the file will
be overwritten. i o s : : a p p will append any records
written to file.
Passing the file name and mode to the constructor in
this way also opens the file for writing.
N o t e that it is unnecessary to write i o s : : o u t so the
line could have been written o f s t r e a m
outClientFile( "clients.txt") ;

Exercise 70
if (outClientFile.fail())
f a i l ( ) is a member function that the o f s t r e a m object
o u t F i l e inherits.
If for some reason the file cannot be opened for writing
an error message is given and the function e x i t called
and the program terminates.
However it is most unlikely the exit function will be
called as if the file does not exist one is created.
Exercise 71
w h i l e ( c o u n t < i n t S t o r e . s i z e ( ) ) uses a w h i l e loop
to loop through vector i n t S t o r e .
Member function s i z e ( ) gets the number of elements
in the vector to control the while loop outputting each
element to file followed by the return character e n d l .

November 2008 213 OUCS


DPFE C++

Step 1
outFile << intStore.at(count)<<endl;
o u t F i l e is the object that points to the file
Numbers.txt.
Each element in the i n t S t o r e vector is passed to file
together with the end of line character using stream
insertion operators < < .
o u t F i l e . c l o s e ( ) ; closes the file.

Step 2
Let’s see how to read from file.
ifstream inFile( "Numbers.txt", ios::in );
The statement above creates an instance of i f s t r e a m
called i n F i l e . The i f s t r e a m constructor takes two
arguments, the name of the file and how the file should
be opened, in this case we are reading i n .
i n F i l e . c l e a r ( ) ; resets e o f for input, though this is
not really necessary here as i n F i l e has just been
created.
i n F i l e . s e e k g ( 0 ) ; positions pointer to beginning of
file, again as we’ve just created i n F i l e , it’s not strictly
necessary.
Step 3
If(inFile.fail())
f a i l ( ) is a member function that the i f s t r e a m object
i n F i l e inherits.
If for some reason the file cannot be opened for
reading (wrong name or no file) an error message is
given and the function e x i t called and the program
terminates.
Step 4
while(!inFile.eof())
{
inFile >> r;
storeSort.push_back(r);
}
The while loop reads the integers input stream object
i n F i l e while not meeting the end of file character.
Each integer is stored in variable r and then pushed
onto the vector s t o r e S o r t .
i n F i l e . c l o s e ( ) ; closes the file.

OUCS 214 November 2008


C++ DPFE

Step 5
The statement s t o r e S o r t . e r a s e ( s t o r e S o r t . e n d ( ) -
1 ) ; removes the last element of the vector. This is
necessary because after the last record (integer) is
passed to file the end of line character is also passed.
The effect of passing e n d l is to create an additional
record. See the statement below which was used
earlier in the program to pass vector elements to file.
outFile << intStore.at(count)<<endl;

Step 6
s o r t ( s t o r e S o r t . b e g i n ( ) , s t o r e S o r t . e n d ( ) ) ; s o r t is
an algorithm that uses random access iterators.
The s o r t ( ) algorithm sorts the elements in the range
[ s t o r e S o r t . b e g i n ( ) , s t o r e S o r t . e n d ( ) ] into
ascending order with the elements being compared
using a default < (less than) operator.

Step 7
for (int i = 0; i < storeSort.size(); i++)
outputLine(storeSort[i]);
The f o r loop is used to iterate through the vector
passing each element in turn to the function
o u t p u t L i n e where it is output.
A static counter in the function o u t p u t L i n e (not
shown here) is used to add an end of line character and
create a new line after ten integers have been output.

Task 2
Modify the file so when
the program is run
additional records are
appended to the file.

23.7. Using the vector class container

Vectors are a kind of sequence container with their elements ordered following a
strict linear sequence.
Vector containers have their elements stored in contiguous memory locations,
similar to arrays. The elements can be accessed not only using iterators but also
using the subscript operator [ ] in the same way as with arrays.

November 2008 215 OUCS


DPFE C++

Unlike arrays, storage in vectors is handled automatically allowing it to be


expanded and contracted as needed. As more data has to be added to the vector a
larger contiguous area of memory is allocated and the existing elements copied
into the new memory. The old memory is then de-allocated.
Vectors are efficient when:
 Accessing individual elements by their position index.
 Iterating over the elements in any order.
 Adding and removing elements but only from the end of the vector.

As we will see, insertions and deletions can actually be made anywhere in the
container but this process is less efficient than methods provided by the other
containers, list and deque.
Vectors are most commonly used when the data has to be sorted and accessible
via a subscript operator, m y V e c t o r [ 1 0 ] ;
Vectors support r a n d o m a c c e s s i t e r a t o r s and this means all the operations
shown in Table 14 can be applied to the class objects.
This also means that all STL algorithms will operate on a vector object. This is
because random access iterators combine their own functionality together with
the functionality of all the other iterator categories.

Exercise 72 Vectors, iterators and algorithms


 Examine the code to recognise and understand iterators & algorithms
 Modify the program

Task 1 Exercise 73
Open V e c s A n d I t s in Open V e c s A n d I t s and examine the code.
the V e c t o r s a n d Only the parts that relate to vectors, iterators and
I t e r a t o r s folder and
algorithms are covered.
examine the code to
establish how to read Have a look at the code shown in Figure 183. The
and write files. code shows the function prototype for template
function O u t P u t V e c t o r E l e m e n t s .
Using a function template allows constant references
to vectors holding any kind of object to be passed to
the function and output to screen. In the example we
pass vectors of integers and doubles.
Note the vector reference being passed is a c o n s t a n t
so any iterators we use must also be constant.

OUCS 216 November 2008


C++ DPFE

Figure 183

Exercise 74
In the statements d o u b s . p u s h _ b a c k ( a + 1 . 3 ) ; and
i n t s . p u s h _ b a c k ( a + 1 ) ; we use the vector member
function p u s h _ b a c k ( ) .
p u s h _ b a c k is available to all sequence containers
and pushes additional data to the back of the vector,
either into elements that are empty or by allocating
additional memory and increasing the size of the
vector.

Exercise 75
The statement O u t P u t V e c t o r E l e m e n t s ( i n t s ) ;
passes the vector i n t s to the template function.

Exercise 76
Examine the code shown in Figure 184. The
statement is used to create a constant reverse iterator
called c o n R e v I t .
Notice that c o n s t _ r e v e r s e _ i t e r a t o r is a f o r w a r d
o n l y iterator, see Table 14.
This means, as the names suggest the iterator can only
move forwards through the container.
Importantly, f o r w a r d i t e r a t o r s do not support the <
“less than" operator.

Figure 184

Exercise 77
Figure 185 shows the creation of another constant
reverse iterator (a forward iterator) being initialised
with the iterator returned from r e n d ( ) .
The significance of this is explained in the next step.

November 2008 217 OUCS


DPFE C++

Figure 185

Exercise 78
In Figure 186 the f o r loop condition is testing to see if
the iterator c o n R e v I T is not equal to iterator
conTempIT.
It would seem intuitive to write this conditional
statement as c o n R e v I T < c o n R e v I T . r e n d ( )
However, c o n R e v I T is a forward iterator and does
not support the < operator so we assigned the iterator
r e n d ( ) to c o n T e m p I T (Figure 185) and use the two
iterators as a comparison condition using operator ! =
see Figure 186 .

Figure 186

Exercise 79
The statement shown in Figure 187 creates a
c o n s t a n t iterator that can read a const element in a
vector.

Figure 187

Exercise 80
In Figure 188 the f o r loop condition is testing to see if
the iterator c o n I T is less than the iterator returned by
inValue.end().
N o t e that we can use the test condition operator <
(less than), as c o n I T is a random- a c c e s s iterator.

OUCS 218 November 2008


C++ DPFE

Figure 188

Task 1
Modify the program to
read from file i n t s . t x t
all the values into a
vector of integers. Show
the vector before and
after sorting.
Read in the values from
d o u b s . t x t . Use the
template function to
show the vector before
and after sorting.
The output should be
similar to Figure 189 Figure 189

Exercise 81 Calculating the min, max and mean of vector elements


 Import data into vector
 Establish the max, min and mean values

Task 1 Exercise 82
Create a new project. The max and min values can be established using the
STL algorithms, m a x _ e l e m e n t and m i n _ e l e m e n t .
Read the data from the
file d o u b s . t x t into a m a x _ e l e m e n t returns an iterator pointing to the
vector. largest element in a range and m i n _ e l e m e n t returns
an iterator pointing to the smallest element in a range.
Establish the max,
minimum and mean The format for m i n _ e l e m e n t is shown in Figure 190.
values in the vector. You will also need to create a vector iterator to assign
the returned iterator to. In this example it’s called
myIterator,
m y I t e r a t o r can be used with the dereference
operator to output the minimum and maximum
values, see Figure 191.
Note, remember to include the header < a l g o r i t h m > .

November 2008 219 OUCS


DPFE C++

Figure 190

Figure 191

Exercise 83
Create a template function that can take any kind of
vector and the code necessary to calculate the m e d i a n
of a range.
If a vector has an odd number of elements the median
is middle vector element, otherwise the median is
(sum of the middle two elements of the vector / 2).
The completed program when run should look similar
to Figure 192.

Exercise 84

Figure 192

OUCS 220 November 2008


C++ DPFE

23.8. Using the list class container


Lists containers are a type of sequence container similar to vectors with their
elements ordered following a linear sequence.
Lists provide an efficient method for insertion and deletion operations at a n y
l o c a t i o n in the container. A vector is efficient when inserting and deleting at the
e n d and deques are efficient when inserting and deleting at the f r o n t and b a c k
of a container.
Lists are implemented as double-linked lists that store each of the elements they
contain in different and u n r e l a t e d s t o r a g e l o c a t i o n s . The ordering is kept by
the association to each element of a l i n k to the element p r e c e d i n g i t , and a l i n k
to the element f o l l o w i n g i t .
Some of the advantages of using list containers are:
 Efficient insertion and removal of elements a n y w h e r e in the container
 Efficient moving elements and block of elements within the container or even
between different containers
 Iterating over the elements in forward or reverse order

Compared to other sequence containers (vectors and deques), l i s t s perform


generally b e t t e r with i n s e r t i o n , e x t r a c t i o n and m o v i n g elements in any
position within the container.
The main d r a w b a c k with using lists compared to these other sequence
containers is that they l a c k d i r e c t a c c e s s t o t h e e l e m e n t s b y t h e i r
p o s i t i o n as they cannot use the subscript operator [ ] .
To access any element in a list one has to iterate from a known position (the
beginning or the end) to that position which takes linear time in the distance
between these elements. Vector and deque can both directly reference any
element using the subscript [ ] operator.

Exercise 85 Using the list container


 Examine how a list is structured, accessed and modified using member
functions
 Create a new program using member functions and algorithms
Task 1 Exercise 86
Open L i s t s A n d I t s file Only the parts that relate to l i s t s , i t e r a t o r s and
in the L i s t s a n d a l g o r i t h m s are covered.
I t e r a t o r s folder and
The code shown in Figure 193 shows the instantiation
examine the code to of two iterators that will be used with list containers
establish how to use the holding data type double.
list container.

November 2008 221 OUCS


DPFE C++

Figure 193

Exercise 87
In Figure 194 the p u s h _ b a c k member function is
used to add values to the end of the list.
L i s t containers also have member functions
p u s h _ f r o n t and p o p _ f r o n t allowing insertion and
removal of elements from the front of the list.

Figure 194

Exercise 88
In Figure 195 a reference is assigned to iterator i t 1 of
the first element in the list d o u b . b e g i n ( ) .
i n s e r t ( ) member function adds an element b e f o r e
the element pointed at by iterator i t 1 .
In this example we are adding 6 9 . 6 9 at the beginning
of the list.
Note: after i n s e r t ( ) iterator i t 1 is still pointing at the
same value in the list that was identified as
d o u b . b e g i n ( ) , i.e. now the second element.
N o t e : this version of the i n s e r t ( ) member function
returns an iterator pointing to the newly added
element. However, as shown here, it does not have to
be used.

Figure 195

OUCS 222 November 2008


C++ DPFE

Exercise 89
In Figure 196 the s o r t ( ) member function is used to
sort the elements in the container from lower to
higher.
Sorting is performed by comparing the elements in
the container in pairs using a sorting algorithm.
The comparisons are performed using the < operator
between the element.

Figure 196

Exercise 90
In Figure 197 the s o r t ( ) member function is used sort
the list d o u b s ( ) .
The merge member function is then used to merge
d o u b s with list d o u b , the merge is to list d o u b .
N o t e that this will empty the second list d o u b s .

Figure 197

Exercise 91
In Figure 198 we want to copy the contents of d o u b ( )
list to the now empty list d o u b s ( ) . To do this we use
the c o p y ( ) algorithm.
The c o p y algorithm uses i n p u t i t e r a t o r and o u t p u t
i t e r a t o r that are supported by l i s t containers
N o t e : before using the c o p y algorithm the list
d o u b s ( ) has to be resized using list member function
r e s i z e ( ) to match the size and number of elements
that will copied into it.

November 2008 223 OUCS


DPFE C++

Figure 198

Exercise 92
In Figure 199 the u n i q u e member function removes
all but the first element from every consecutive group
of equal elements in the list container.
Elements are only removed from the list if they are
equal to the element immediately preceding it.
Therefore a list should be sorted first before using this
member function.

Figure 199

Exercise 93
Figure 200 shows how to exchange the content of the
list d o u b with the content of d o u b s .
Obviously both lists must contain elements of the
same type but list s i z e s may differ.
After the call to the member function the elements in
d o u b container are those which were in d o u b s , and
the elements of d o u b s are those which were in d o u b .
N o t e that an a l g o r i t h m exists with the same name
s w a p , which has the same behaviour.

Figure 200

OUCS 224 November 2008


C++ DPFE

Exercise 94
In Figure 201 iterator i t 1 is positioned at the start of
the list using function b e g i n ( ) .
STL class iterator a d v a n c e ( ) advances the iterator
i t 1 , twice to the third element of the d o u b list.
Iterator i t 1 will be used with the s p l i c e ( ) member
shown in Figure 202.

Figure 201

Exercise 95
Figure 202 member function s p l i c e ( ) is used to move
elements from list to list.
Elements are moved from m y L i s t into the list
container d o u b at the specified position i t 1 .
N o t e : iterator i t 1 has already been moved to the third
element position.
The element at location i t 2 in m y L i s t , “10” is moved
from m y L i s t into list d o u b .
m y L i s t has one element less and d o u b has one
element added at position i t 1 .

Figure 202

November 2008 225 OUCS


DPFE C++

Exercise 96
Figure 203 shows how to use the s p l i c e member
function with a different template. This function
template needs four parameters.
P a r a m e t e r 1 is the position in the container where
the elements of m y L i s t are inserted; d o u b . b e g i n ( ) .
P a r a m e t e r 2 is the list object m y L i s t containing the
same type of objects as d o u b container.
P a r a m e t e r s 3 & 4 are iterators specifying a range of
elements in m y L i s t . The elements in this range are
moved to d o u b . b e g i n ( ) .
Notice that the range includes all the elements
between i t 1 and m y L i s t . e n d ( ) the element pointed
by i t 1 but not the one pointed by m y L i s t . e n d ( ) as
this points past the last element in the list.

Figure 203

Task 1 Exercise 97
Create a new project, call Create a l i s t and l i s t i t e r a t o r .
it L i s t F i n d A n d Load the file L i s t N u m b e r s . t x t to the l i s t .
Erase

Exercise 98
Use the f i n d ( ) STL algorithm (there is no member
function) to return an iterator to the position in the
list of a known number.
it = find (myList.begin(), myList.end(), anInt);

Exercise 99
Add a number of your choice together with the
returned iterator from f i n d to the i n s e r t member
function. The statement should be similar to
myList.insert (it,value);

OUCS 226 November 2008


C++ DPFE

Exercise 100
Insert the elements from a vector into the list from the
beginning of the list. See Figure 204 for a possible
way to achieve this.

Figure 204

Exercise 101
Find the three digit number in the list and erase it.
The program when completed and run should look
similar to Figure 205

Figure 205

November 2008 227 OUCS


DPFE C++

23.9. Using the deque class container


The d e q u e class provides many of the benefits of a vector and a list in one
container. Deque, normally pronounced "deck" is short for double-ended queue.
Double-ended queues are sequence containers and as such their elements are
ordered following a strict linear sequence. With a d e q u e it is possible to use
i n d e x i n g to access individual elements for reading and writing in a similar way
to that used with vectors.
The d e q u e sequence container provides similar functionality to vectors but with
efficient insertion and deletion of elements at the beginning and end of the
sequence in a similar way as done with lists.
Lists have an advantage over d e q u e s in that they can also insert and delete
elements efficiently from the middle of the container. However, insertions can be
made at positions other than the front and back (there is an i n s e r t and e r a s e
d e q u e member function) but this is l e s s e f f i c i e n t than using a l i s t container.
It is worth noting that unlike vectors, d e q u e s are not guaranteed to have all its
elements in contiguous storage locations. The elements of a deque can be divided
in several areas of memory with the class keeping all necessary information and
providing uniform access to the elements.
Because of the above, a d e q u e will grow more efficiently than a vector (where
large reallocations of memory are necessary as the vector grows) with its capacity
managed automatically.
The d e q u e class also provides support for random access iterators so can use all
STL algorithms.

Deque containers have the following properties:


• Individual elements can be accessed by their position index.
• Iteration over the elements can be performed in any order.
• Elements can be efficiently added and removed from either end.

Both v e c t o r s and d e q u e s provide a very similar interface and can be used for
similar purposes, but internally both work in quite different ways.

OUCS 228 November 2008


C++ DPFE

Exercise 102 Using the deque container


 Examine some of the member functions of the deque container
 Create a program to find and remove records in a deque container

Task 1 Exercise 103


Open D e q u e A n d I t s file Only parts of the code that relate to deques are
in the D e q u e s a n d covered. All other coding is covered in previous
I t e r a t o r s folder and exercises
examine the code to The code shown in Figure 206 shows the use of deque
establish how to use the member functions p u s h _ b a c k and p u s h _ f r o n t
d e q u e container.
adding elements at the back and front of the deque in
a similar way as done with lists.

Figure 206

Exercise 104
Figure 207 shows how to use the s o r t ( ) algorithm,
elements are sorted into ascending order.
Class deque does not have a member function sort,
but we can make use of the s o r t ( ) alogorithm.
m y D e q u e . b e g i n ( ) and m y D e q u e . e n d ( ) return
random-access iterators to the initial and final
positions of the sequence to be sorted.

Figure 207

November 2008 229 OUCS


DPFE C++

Exercise 105
Figure 208 shows how to use the i n s e r t ( ) member
function with d e q u e .
The d e q u e container is extended by inserting new
elements before the element at the specified position.
This increases the container size by the amount of
elements inserted.
Remember that deques are designed to be efficient at
performing insertions (and removals) from either end
of the sequence.
Insertions and deletions on other positions are less
efficient. If you need to do this it’s best to use a l i s t
container.

Figure 208

Exercise 106
Figure 209 shows the deletion of a deque element
other than at the end of the container.
m y D e q u e . b e g i n ( ) + 5 returns an iterator to the
element to be erased, in the middle of the deque.
Remember that if you intend to insert or erase
elements from the middle of your container it is more
efficient to use a l i s t .

Figure 209

OUCS 230 November 2008


C++ DPFE

Exercise 107
Examine the code in Figure 210. In this example we
are using the i n s e r t function with a different number
of parameters.
The parameters here indicate where in the d e q u e the
elements will be inserted (i t 1 ) and the range of
elements to be inserted m y V e c . b e g i n ( ) to
myVec.end().
N o t e that the element pointed to by m y V e c . e n d ( ) is
not copied.

Figure 210

Task 1
Modify the program in
D e q u e A n d I t s . d e v so
only the first two
elements in m y V e c are
copied to the deque.

November 2008 231 OUCS


DPFE C++

23.10. Using the multiset associative container


The STL m u l t i s e t class is used for the storage and retrieval of data from a
collection in which the v a l u e s of the e l e m e n t s contained need n o t be u n i q u e
and in which they serve as the k e y values according to which data is
automatically ordered.
The k e y value of an element in a m u l t i s e t may not be changed directly. Instead,
old values must be d e l e t e d and elements with new values i n s e r t e d .
N o t e that u n l i k e the m u l t i s e t class, the s e t class is used for the storage and
retrieval of data from a collection in which the v a l u e s of the e l e m e n t s
contained are u n i q u e and also serve as key v a l u e s .

Exercise 108Using the multiset container


 Learn how to structure and manipulate data in multiset containers

Task 1 Exercise 109


In eclipse, open the The header file for m u l t i s e t and s e t is the same and
project MultiSet must be included to allow use of member functions,
project file in the see Figure 211.
Multiset Container
folder and examine the
code to establish how to
use the m u l t i s e t
container.

Figure 211

Exercise 110
In Figure 212 the t y p e d e f keyword creates an alias
called m u l t S e t for a m u l t i s e t container data type.
T h e e f f e c t o f t h i s s t a t e m e n t i s t o s o r t the
m u l t i s e t from l o w e s t to h i g h e s t .

Figure 212

OUCS 232 November 2008


C++ DPFE

t y p e d e f s can be created for most data types but this


does not create different types, it only creates
synonyms of existing types with names of our choice.
Figure 213 shows common t y p e d e f s being created
and used in declarations.

Figure 213
It is useful to define types when it is possible that the
d a t a t y p e will change in later versions of the
program, or if a type you want to use has a name that
is too long or confusing.

Exercise 111
The statement shown in Figure 212 uses the
l e s s < i n t > function object for less-than inequality
comparison.
l e s s has its operator ( ) member defined such that it
returns t r u e if its f i r s t argument compares lower
than the second one using operator < , and f a l s e
otherwise.
The effect of "l e s s " is to s o r t the m u l t i s e t from
l o w e s t to h i g h e s t .
To sort from highest to lowest use "g r e a t e r " function
object.

Exercise 112
Figure 214 shows the c o u n t ( ) member function being
used to search the container for an element with a key
of 1 5 .
The function returns the number of times the element
appears in container i n t M u l t i s e t .

November 2008 233 OUCS


DPFE C++

Figure 214

Exercise 113
Figure 215 shows the creation of constant iterator
called r e s u l t .
The scope resolution operator : : is used to enable the
name of the member that follows the operator
(c o n s t _ i t e r a t o r ) to be looked up in the scope of the
class with the name that appears before the operator.
The correct type of iterator is then created, in this case
for multiset, b i d i r e c t i o n a l .

Figure 215

Exercise 114
Figure 216 shows the use of the f i n d ( ) member
function which returns a bidirectional iterator.
The function is used to search the container for an
element with a value of 1 5 and return the iterator to it
if found.
If the value is not found an iterator to
m u l t i s e t : : e n d ( ) is returned. The e n d ( ) iterator
points to the element past the end of the container
and it is possible to test for this.

Figure 216

OUCS 234 November 2008


C++ DPFE

Exercise 115
The code shown in Figure 217 tests to see if the
returned iterator points to the end of the multiset.
In Figure 217 the returned iterator type is used to
determine the output.

Figure 217

Exercise 116
Figure 218 shows the use of i n s e r t member function
to extend the container by adding all of array a
elements.
a and a + S I Z E are iterators specifying a range of
elements to be inserted into the multiset. From the
beginning to the end of the array a .

Figure 218

Exercise 117
In Figure 219 l o w e r _ b o u n d returns an iterator
pointing to the first element in the container which
does not compare less than 2 4 (using the container's
comparison object, defined in t y p e d e f , in this case
l e s s ).
A pointer is returned to a value that is either equal to
or greater than the key value, d e r e f e r e n c e d here.

Figure 219

November 2008 235 OUCS


DPFE C++

Exercise 118
Figure 220 shows u p p e r _ b o u n d member function
which returns an iterator pointing to the first element
in the container which compares greater than the k e y ,
2 4 (using the container's comparison object, l e s s ).
Unlike l o w e r _ b o u n d , this member function does not
return an iterator to the element if it compares equal
to 24, but only if it compares strictly g r e a t e r .
If the iterator is passed the container last element its
equal to i n t M u l t i s e t . e n d ( ) so we test for this, if this
is true the key cannot in multiset so output
accordingly.

Figure 220

Exercise 119
Figure 221 shows the use of the p a i r s utility
components. p represents a pair of c o n s t _ i t e r a t o r s ,
in this case m u l t S e t c o n s t _ i t e r a t o r s .
The p a i r class couples together a pair of values, which
may be of different types. The individual values are
accessed through the public members f i r s t and
second.

Figure 221

OUCS 236 November 2008


C++ DPFE

Exercise 120
Figure 222 shows the member function e q u a l _ r a n g e
returning a pair of iterators, p . f i r s t and p . s e c o n d .
Member p . f i r s t is an iterator to the lower bound of
the range with the same value as would be returned by
lower_bound(key).
p . s e c o n d is an iterator to the upper bound of the
range with the same value as would be returned by
upper_bound(key).
So it’s another way to get l o w e r _ b o u n d and
u p p e r _ b o u n d values.

Figure 222

Exercise 121
The values pointed at by the returned iterators are
output using the d e r e f e r e n c e operator and the
members as shown in Figure 223.

Figure 223

Task 1 Exercise 122


Create a new The class member functions you will need are f i n d
project, call it Multi and e r a s e .
SetFind.
f i n d returns an iterator and e r a s e uses an iterator as
The program will import an argument.
a text file (Numbers.txt)
containing integers into
a multiset.
The user will be
prompted to add a
number to find and then
erase in the multiset.
If the number is not
found the user should be
informed of such. The
modified multiset should
be displayed.
Figure 224
See Figure 224.

November 2008 237 OUCS


DPFE C++

23.11. Using the multimap associative container


M u l t i m a p s and m a p s are both kinds of associative containers that are formed
by the combination of a k e y v a l u e and a m a p p e d v a l u e .
Each container stores values with the associated k e y used to identify each
element. M u l t i m a p s allow the use of duplicate k e y s , m a p containers d o n o t
have duplicate keys.
The ordering of m u t i m a p keys is done in a similar way as done with m u l t i s e t by
using a c o m p a r a t o r f u n c t i o n o b j e c t . A m u l t i m a p that uses integers as the
key type can be sorted in ascending order with the function object l e s s < i n t > .
Many of the functions we have seen when using m u t i l i s t are also available for
use with m u l t i m a p s .

Exercise 123 Using the mutimap container


 Learn how to structure and manipulate data in multimap containers

Task 1 Exercise 124


In eclipse, open the The header file for m u l t i m a p and m a p is the same
p r o j e c t M u l t i m a p in and must be included to allow use of member
the M u l t i M a p functions, see Figure 225.
C o n t a i n e r folder and
examine the code to
establish how to use the
m u l t i m a p container.

Figure 225

Exercise 125
Figure 226 shows the creation of an instance of
t y p e d e f m u l t m a p called c C a r d N o .

Figure 226

OUCS 238 November 2008


C++ DPFE

Exercise 126
In Figure 227 two v a l u e _ t y p e objects are inserted in
c C a r d N o multimap. The values entered are integers
and doubles for the k e y & v a l u e of the first two
elements.
v a l u e _ t y p e is a synonym for t y p e as defined in the
t y p e d e f for multimap at the start of the program, in
this case the k e y is type i n t and the v a l u e type
double.

Figure 227

Exercise 127
Figure 228 shows the use of a c o n s t _ i t e r a t o r named
i t e r to run through c C a r d N o multimap using pointer
notation to access members f i r s t and s e c o n d .
The iterator defined by m u l t i m a p points to objects of
v a l u e _ t y p e which are of type p a i r <c o n s t K e y ,
Type>.
The value of the K e y is available through the first
member pair and the value of T y p e of the mapped
element is available through the second member of
the pair.
To dereference an iterator i t e r pointing to an element
in a m u l t i m a p we use the arrow - > operator.
To access the value of the key for the element, use i t e r
- > f i r s t which is equivalent to ( * i t e r ) . f i r s t .
To access the value of the mapped data for the
element use i t e r - > s e c o n d which is equivalent to
(*Iter).second.

Figure 228

November 2008 239 OUCS


DPFE C++

Task 1 Exercise 128


Create a new project, call Read all the records into a m u l t i m a p using a while
it C r e d i t C a r d . loop similar to Figure 229.
The program should
read in the card numbers
and transactions for the
50 customers detailed in
cardNumbers.txt.
There are 159
transactions by 50 Figure 229
customers. We need to
see the sum of all
transactions for the first
20 customers (ID’s 1-20)
together with a total of
all transactions for the
twenty account holders.
The program should look
similar to Figure 230
when run.

Figure 230

Exercise 129
Use the m u l t i m a p c o u n t ( ) member function in a f o r
loop to total the number of transactions for each of
the first twenty account holders, see Figure 231.

Figure 231

OUCS 240 November 2008


C++ DPFE

Exercise 130
Still inside the f o r loop add code similar to Figure
232.
The function e q u a l _ r a n g e returns a p a i r , where its
member p a i r : : f i r s t is an iterator to the lower bound
of the range (ex the first of many 1's).
p a i r : : s e c o n d is an iterator to the upper bound of the
range (ex the last of many 1's).
i n d t o t a l is the sum of the mapped v a l u e for each
transaction for each account.

Figure 232

Task 1
Modify the program to
send the total
transactions for each of
the first 20 customers
(ID’s 1-20) to file.
Save the file as
clientsDebt.txt.
The file should look the
same as Figure 233

Figure 233

November 2008 241 OUCS


DPFE C++

23.12. More on using algorithms


Algorithms do not work with containers themselves but rather with i t e r a t o r s .
Therefore, the same algorithm can be used by most if not all of the STL
containers.
When you start using STL algorithms you will need to write functions called
u n a r y p r e d i c a t e s . These are functions that take a single parameter and return
a B o o l e a n value.
A f u n c t i o n o b j e c t , or f u n c t o r (the two terms are synonymous) is simply any
object that can be called as if it is a function. An ordinary function is a function
object. Function objects that return bool are an important special case.
A unary function whose return type is b o o l is called a p r e d i c a t e , and a binary
function (two arguments) whose return type is b o o l is called a B i n a r y
Predicate.
Predicates are used when you might want to copy only a well-defined subset of
one sequence to another. Perhaps when elements meet a particular condition: > ,
< , = = etc.
To achieve this flexibility, many algorithms have alternate calling sequences that
allow you to supply a p r e d i c a t e .
Suppose, for example, that we want to extract from a sequence of integers those
numbers that are less than or equal to 69.
A version of c o p y ( ) algorithm called r e m o v e _ c o p y _ i f ( ) can meet the
requirements.
In C++ a f u n c t o r can also be created by defining a class which overloads the
function call operator by defining an operator ( ) member function. This is often
called a c l a s s t y p e f u n c t o r .
Have a look at V e c s A n d I t s project in the A l g o r i t h m s a n d P r e d i c a t e s folder.
Some of the available algorithms together with predicate functions are explained.
Algorithms used in the program:
Operation Type
accumulate algorithm
assign member function
binary_search algorithm
count_if algorithm
find_if algorithm
includes algorithm
max_element algorithm
min_element algorithm
random_shuffle algorithm
replace algorithm
replace_copy algorithm
replace_copy_if algorithm

OUCS 242 November 2008


C++ DPFE

Table 18

November 2008 243 OUCS


DPFE C++

24 Appendix
24.1. Arithmetical Operators

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

24.2. Assignment Operators

Operator Example Equivalent


= a=b a=b
+= a +=b a=a+b
-= a -=b a=a-b
*= a *=b a=a*b
/= a /=b a=a/b
%+ a %=b a=a%b

24.3. Assignment and Arithmetic examples

The a s s i g n m e n t o p e r a t o r in C++ is = .
The format is v a r i a b l e = e x p r e s s i o n ; this can be read as, assign to the
v a r i a b l e the value of the e x p r e s s i o n .
An example to calculate the number of pence in a value in pounds would be:
pence = pounds * 100;
N o t e : it is easy to confuse the assignment operator = with the equals notation
used in mathematics. The equals notation in C++ is = = .

Incrementing a variable.

OUCS 244 November 2008


C++ DPFE

m o n t h = m o n t h + 1 ; adds the value one to the variable m o n t h . This can be


written as m o n t h + + ;
Decrementing a variable.
m o n t h = m o n t h - 1 ; deducts the value one from the variable m o n t h . This can
be written as m o n t h - - ;

In C++ it is also possible to combine arithmetic and assignment operations.

To add 2 to a variable t o t a l :
total = total + 2; or t o t a l + = 2 ;
To subtract 2 from t o t a l :
total = total - 2; or t o t a l - = 2 ;
To multiply t o t a l by 2 :
total = total * 2; or t o t a l * = 2 ;

24.4. Relational and Equality Operators

The equality operator is used to compare two operands ( a = = b ) and returns 1


(t r u e ) if both are equal, otherwise 0 (f a l s e ) is returned.
The inequality operator (! = ) returns 1 (t r u e ) if both are N O T equal, otherwise 0
(f a l s e ) is returned.
Both the above operators are commonly used to test the state of two variables to
perform conditional branching.
The relational operators also return either true or false. (a > = b ) returns 1
(t r u e ) if a is greater than or equal to b, otherwise 0 (f a l s e ) is returned.

Standard algebraic C++ equality or


Sample C+ Meaning of C++
equality or relational relational
+ condition condition
operator operator

Relational operators
> > a>b a is greater than b
< < a<b a is less than b
 >= a >= b a is greater than or equal to b
 <= a <= b a is less than or equal to b
Equality operators
= == a == b a is equal to b
 != a != b a is not equal to b

Table 19

November 2008 245 OUCS


DPFE C++

24.5. Logical Operators


When using i f selection statements it is common to use the relational operators
as part of the test. if(num >5), if(size<=14), if(Char ==’A’). These are fine for
testing one condition.
To test multiple conditions it is possible to nest i f statements but this can be a bit
cumbersome.
Logical Operators can be used to form more complex conditions by combining
simple conditions.

L o g i c a l A N D ( & & ) O p e r a t o r allows a test to see if two conditions are true.


if (leaveBooked > LeaveLeft && staffCover = = false)
cout<<”Take your holidays sometime else”;

L o g i c a l O R ( | | ) O p e r a t o r allows a test to see if either or both of the conditions


are true.
if (Temperature < 16 || windspeed > 15)
cout<<”Too cold or windy to sunbath today then”;

L o g i c a l N e g a t i o n ( ! ) O p e r a t o r reverses the meaning of a condition.


if (!(windspeed == 20))
cout<<”The wind speed is not 20 it’s ”<<windspeed;

This could be written equally as well with the equality operator,


if (windspeed != 20)
cout<<”The wind speed is not 20 it’s ”<<windspeed;

24.6. Escape Sequences

Escape Description
Sequence
\n Newline. Position the screen cursor at the beginning of
the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\r Carriage return. Position the cursor at the beginning of
the current line.
\a Alert. Sound the system bell.
\\ Backslash, used to print a backslash.
\’ Single quote. Use to print a single quote character.
\” Double quote. Used to print a double quote character

OUCS 246 November 2008


C++ DPFE

24.7. Cast Operator


Is where the programmer explicitly asks for a change in data type. It may be that
the result of a calculation is a double and the user wants it to be of type integer.
A double can be cast to an integer in the following way:
int runs = static_cast<int>(x + 0.5);

24.8. Formatted Output


When several numbers are displayed each is printed with the minimum number
of digits needed to show the value. This can yield some unexpected output.
The width of an output field can be set using a stream manipulator. To set the
next number to be printed to a width of 5 digits use cout <<setw(5). This
command does not produce any output it manipulates the stream to change the
output format of the next value. N o t e : s e t w must be specified for every item
output.
To use any stream manipulators you must include the header # i n c l u d e
<iomanip>.
s e t p r e c i s i o n is another manipulator and is used to set the precision of the next
floating point number. N o t e : s e t p r e c i s i o n only has to be set once as the
stream remembers the formatting directive and does not affect integer fields. The
format is c o u t < < s e t p r e c i s i o n ( 3 ) .
To set precision for trailing zeros (0.100 will appear as 0.1) it is necessary to use
the f i x e d format. The command is: c o u t < < f i x e d ; N o t e : f i x e d only has to
be set once.
The three manipulators can be combined to achieve the required precision and
field width when used in this way:
cout << fixed << setprecision(3) << setw(5) << myDouble;
Alternatively as fixed and setprecision only have to be set once this statement
could be written as:
cout << fixed << setprecision(3);
cout << setw(5) << myDouble;

24.9. Header Files


Every program that you create will have at least one header file. If you use input
or output you will have to include the i o s t r e a m header.
If you use mathematical functions you will need c m a t h . It can be difficult to
know which header files to use for each function. Some of the common header
files used, together with some of the older ones you may find with inherited code
are shown below. It is a good idea to use the help if you are unsure which header
files are associated with particular functions.

November 2008 247 OUCS


DPFE C++

Standard C++ header Old header


iostream iostream.h
iomanip iomanip.h
fstream fstream.h
cmath math.h
cstdlib stdlib.h
string No equivalent
vector vector.h
Table 20

24.10. Scope

The portion of a program where an identifier can be used is known as its scope.
An identifier declared outside any function or class has f i l e s c o p e . This type of
identifier is “known” by all functions. Global variables and function prototypes
all have file scope.
Identifiers declared inside a block of code have b l o c k s c o p e . This type of scope
begins at the identifiers declaration and ends at the termination right brace (} ) of
the block in which the identifier is declared.
Any block can contain local variable declarations. If blocks are nested it is
possible to declare variables with the same name in each nested block. The
variable in the outer block is hidden while the inner block is being executed.

24.11. Enumerating constants

The e n u m keyword provides a handy way to create a sequence of integer


constants. An example of enumeration is shown below:
enum Months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT,
NOV, DEC};
Each of the constants will have a default value 1 greater than the constants that it
follows in the list. The first value in the enumeration above is explicitly set to 1
and the remaining values increment by 1. The values assigned from JAN to DEC
will be 1 to 12.
The statement cout<<"DECEMBER is month number "<<DEC <<endl; would
be output as D E C E M B E R i s m o n t h n u m b e r 1 2 .

24.12. Constants

Data that will not change during the execution of a program should be stored in a
constant container rather than a variable. If the program attempts to change the

OUCS 248 November 2008


C++ DPFE

value stored in a constant the compiler will report an error and compilation will
fail.
Constant can be created for any data type by prefixing the declaration with c o n s t
keyword followed by a space. Note: Constants must always be initialised at
declaration.
The following declaration declares a constant for the speed of sound at sea level
m/s.

const double SpeedOfSound = 340.29;

24.13. Vectors member functions

Some commonly used member functions of the vector class are:

Vector member Effect


Functions
at(element number) Gets the value contained in the specified
element
back() Gets the value in the final element
begin() Points to the first element in vector
clear() Erases the vector
empty() Returns true (1) if the vector is empty, or false
(0) otherwise
end() Points to the last element in vector
front() Gets the value in the first element
pop_back Removes the final element
push_back(value) Adds an element to the end of the vector,
containing the specified value
size() Gets the number of elements

24.14. Container global functions

Container global Functions Effect


find(); Finds the element in the container containing
number 67. Needs iterator (ptr) to store location
ptr = find(vec.begin(), vec.end(), 67);
of element.
reverse(); reverse(v.begin() v.end()) Reverses the values in a container (v)
sort(); Sorts the container (v)

November 2008 249 OUCS


DPFE C++

Container global Functions Effect


sort(v.begin(), v.end())

24.15. cmath functions

Function Argument Result Returned Example Result


Value
ceil(x) double double Smallest integer ceil(2.1) 3.0
≥x
cos(x) double double Cosine of x cos(1.0) 0.54
radians
fabs(x) double double Absolute value of fabs(-1.5) 1.5
x
floor(x) double double Largest integer ≤ floor(2.9) 2.0
2.9
pow(x,y) double double x to the yth pow(2,4) 16.0
power
sin(x) double double Sine of x radians sin(1.0) 0.84
sqrt(x) double double Square root of x sqrt(4) 2.0
tan(x) double double Tangent of x tan(1.0) 1.56
radians

24.16. String class

The string class defines many m e m b e r f u n c t i o n s . A few of the basic ones are
described below:

Initialisation - constructors form


A string expression string str2 = str1;
string str3 = ch; where ch is a
character array.
string str4 = cp; where cp is a
pointer to a character array.
A character string literal string Intro = "Programming with
C++";
A substring of another string string Intro = "Capetown";
object string Mytown = "Boars"
string MyTown (Intro,4,5);
starts at character 4 ('t')

OUCS 250 November 2008


C++ DPFE

Initialisation - constructors form


with a length of 5, (or the rest of the
string, if shorter)
cout << myTown << endl;
will produce an output “town”

length() string myName = "Sebastion";


myName.length();
will produce an output of 9.
insert () Inserts a string into the current string,
starting at the specified position.
string myName = " Sebastion";
string nameAdd = "rjio";
myName.insert (2,nameAdd);
cout << myName << endl;
will produce an output “Serjiobastion”

erase() Delete a substring from the current


string.
string myName = " Sebastion";
myName.erase (0,2);
cout << myName << endl;
will produce an output “bastion”
replace() Delete a substring from the current
string, and replace it with another string.

string myName = " Sebastion";


string aName = "renna";
myName.replace (3,6,aName);
cout << myName << endl;
will produce an output “S e b r e n n a ”
substr() Returns a substring of the current
string.
string myName = " Sebastion";
string aName = myName.substr
(0,3);
cout << aName << endl;
will produce an output “S e b ”

November 2008 251 OUCS


DPFE C++

Non-member functions

string name;

getline() getline(cin, name);

24.17. Pointer based String Manipulation Functions

Function prototype Description


char *strcpy(char *a1, const char *a2);

Copies the string a2 into the char array a1. The value of
a1 is returned.
E x a m p l e : strcpy(a1, a2); copy the contents of array a2 into array a1.
N o t e : the programmer must ensure the first array (a1) is large enough to store the string in
a2.
char *strncpy(char *a1, const char *a2, size_t n);

Copies at most n characters of the string a2 into the


character array a1. The value of a2 is returned.
E x a m p l e : strncpy(a1, a2, 10); copy the first 10 characters from array a2 into array a1.
N o t e : must add the null character manually to terminate the string properly.
a1[10] = ‘\n’;
char *strcat(char *a1, const char *a2);.
Appends the string a2 to a1. The first character of a2
overwrites the null character of a1. The value in a1 is
returned.
E x a m p l e : strcat(a1, a2); concatenate a2 to a1.
N o t e : the programmer must ensure the first array is long enough to store the combination
of the two strings and the null character copied from the second string a2.
char *strncat(char *a1, const char *a2, size_t n);.
Appends at most n characters of string a2 to a1. The
first character of a2 overwrites the null character of a1.
The value in a1 is returned.
E x a m p l e : strncat(a1, a2, 6); concatenate the first 6 characters of a2 to a1.
N o t e : the programmer must ensure the first array is long enough to store the combination
of the two strings and the null character automatically added to terminate the string.
int strcmp(const char *a1, const char *a2);.
Compares the string a1 with string a2. The function
returns a value of zero, less than zero (usually -1) or
greater than zero (usually 1) if a1 is equal to, less than or
greater than a2, respectively. This function compares

OUCS 252 November 2008


C++ DPFE

Function prototype Description


array element 0 for each array and progresses through
the array.
E x a m p l e : strcmp(a1, a2); compares the characters in the two arrays.

int strncmp(const char *a1, const char *a2, size_t n);.


Compares up to n - characters of string a1 with a2. The
function returns zero, less than zero (usually -1) or
greater than zero (usually 1) if n character portion of a1
is equal to, less than or greater than the corresponding
n -character portion of a2, respectively.
E x a m p l e : strcmp(a1, a2, 6); compares the first 6 characters in the two arrays.
N o t e : function strncmp stops comparing characters if it reaches the null character in one
of the string arguments. The program prints the integer value returned.
char *strtok(char *a1, const char *a2)
A sequence of calls to strtok breaks string a1 into ‘tokens’
or logical pieces such as words. The string is broken up
based on the characters in a2. A string “Welcome to
OUCS” could be broken up using the character “ “
(space). This would create three tokens, “Welcome”, “to”
and “OUCS”. strtok returns a pointer to the current
token.
Example: myPtr is a pointer to char.
char a1 [] = “Welcome to OUCS”
myPtr = strtok(a1, “ “); searches for tokens in the string, the separator is “ “ .
Note: that if the array is printed out after tokenisation only the first token will be printed.
This is because the token separators are replaced by ‘\n’ null character during tokenisation..
size_t strlen(const char *a)
This function determines the length of string a. The
number of characters preceding the terminating null
character is returned.
E x a m p l e : strlen(a1); gets the number of characters in array ‘a1’.

Note: the above function prototypes are located in the header file < c s t r i n g > .

24.18. Constant Objects and const Member functions.


Some of the objects that you will create in programs will need to be modifiable
and some will not. We can use the keyword c o n s t to specify that an object is not
modifiable and that any attempt to modify it will result in a compilation error.

November 2008 253 OUCS


DPFE C++

const Staff Peter(“12/8/78”,8,”OX34 7TY”); declares a c o n s t object


P e t e r of class S t a f f and initialises the D O B , H o u s e N o and p o s t c o d e .
Declaring an object as c o n s t helps enforce the principle of least privilege
improving the objects information hiding capabilities. Objects should be able to
communicate with each other across interfaces but implementation details
should be hidden. Any attempt to modify a c o n s t object will be caught at
compile time rather than causing errors when the program executes.

24.19. ASCII Character set

Decim
al Octal Hexadecimal Binary Value
0 0 0 0 NUL (Null char.)
1 1 1 1 SOH (Start of Header)
2 2 2 10 STX (Start of Text)
3 3 3 11 ETX (End of Text)
4 4 4 100 EOT (End of Transmission)
5 5 5 101 ENQ (Enquiry)
6 6 6 110 ACK (Acknowledgment)
7 7 7 111 BEL (Bell)
8 10 8 1000 BS (Backspace)
9 11 9 1001 HT (Horizontal Tab)
10 12 00A 1010 LF (Line Feed)
11 13 00B 1011 VT (Vertical Tab)
12 14 00C 1100 FF (Form Feed)
13 15 00D 1101 CR (Carriage Return)
14 16 00E 1110 SO (Shift Out)
15 17 00F 1111 SI (Shift In)
16 20 10 10000 DLE (Data Link Escape)
17 21 11 10001 DC1 (X ON) (Device Control 1)
18 22 12 10010 DC2 (Device Control 2)
19 23 13 10011 DC3 (X OFF)(Device Control 3)
20 24 14 10100 DC4 (Device Control 4)
21 25 15 10101 NAK (Negative Acknowledgement)
22 26 16 10110 SYN (Synchronous Idle)
23 27 17 10111 ETB (End of Trans. Block)
24 30 18 11000 CAN (Cancel)
25 31 19 11001 EM (End of Medium)
26 32 01A 11010 SUB (Substitute)
27 33 01B 11011 ESC (Escape)
28 34 01C 11100 FS (File Separator)
29 35 01D 11101 GS (Group Separator)
(Request to Send)(Record
30 36 01E 11110 RS Separator)
31 37 01F 11111 US (Unit Separator)
32 40 20 100000 SP (Space)

OUCS 254 November 2008


C++ DPFE

Decim
al Octal Hexadecimal Binary Value
33 41 21 100001 ! (exclamation mark)
34 42 22 100010 " (double quote)
35 43 23 100011 # (number sign)
36 44 24 100100 $ (dollar sign)
37 45 25 100101 % (percent)
38 46 26 100110 & (ampersand)
39 47 27 100111 ' (single quote)
40 50 28 101000 ( (left/opening parenthesis)
41 51 29 101001 ) (right/closing parenthesis)
42 52 02A 101010 * (asterisk)
43 53 02B 101011 + (plus)
44 54 02C 101100 , (comma)
45 55 02D 101101 - (minus or dash)
46 56 02E 101110 . (dot)
47 57 02F 101111 / (forward slash)
48 60 30 110000 0
49 61 31 110001 1
50 62 32 110010 2
51 63 33 110011 3
52 64 34 110100 4
53 65 35 110101 5
54 66 36 110110 6
55 67 37 110111 7
56 70 38 111000 8
57 71 39 111001 9
58 72 03A 111010 : (colon)
59 73 03B 111011 ; (semi-colon)
60 74 03C 111100 < (less than)
61 75 03D 111101 = (equal sign)
62 76 03E 111110 > (greater than)
63 77 03F 111111 ? (question mark)
64 100 40 1000000 @ (AT symbol)
65 101 41 1000001 A
66 102 42 1000010 B
67 103 43 1000011 C
68 104 44 1000100 D
69 105 45 1000101 E
70 106 46 1000110 F
71 107 47 1000111 G
72 110 48 1001000 H
73 111 49 1001001 I
74 112 04A 1001010 J
75 113 04B 1001011 K
76 114 04C 1001100 L

November 2008 255 OUCS


DPFE C++

Decim
al Octal Hexadecimal Binary Value
77 115 04D 1001101 M
78 116 04E 1001110 N
79 117 04F 1001111 O
80 120 50 1010000 P
81 121 51 1010001 Q
82 122 52 1010010 R
83 123 53 1010011 S
84 124 54 1010100 T
85 125 55 1010101 U
86 126 56 1010110 V
87 127 57 1010111 W
88 130 58 1011000 X
89 131 59 1011001 Y
90 132 05A 1011010 Z
91 133 05B 1011011 [ (left/opening bracket)
92 134 05C 1011100 \ (back slash)
93 135 05D 1011101 ] (right/closing bracket)
94 136 05E 1011110 ^ (caret/cirumflex)
95 137 05F 1011111 _ (underscore)
96 140 60 1100000 `
97 141 61 1100001 a
98 142 62 1100010 b
99 143 63 1100011 c
100 144 64 1100100 d
101 145 65 1100101 e
102 146 66 1100110 f
103 147 67 1100111 g
104 150 68 1101000 h
105 151 69 1101001 i
106 152 06A 1101010 j
107 153 06B 1101011 k
108 154 06C 1101100 l
109 155 06D 1101101 m
110 156 06E 1101110 n
111 157 06F 1101111 o
112 160 70 1110000 p
113 161 71 1110001 q
114 162 72 1110010 r
115 163 73 1110011 s
116 164 74 1110100 t
117 165 75 1110101 u
118 166 76 1110110 v
119 167 77 1110111 w
120 170 78 1111000 x

OUCS 256 November 2008


C++ DPFE

Decim
al Octal Hexadecimal Binary Value
121 171 79 1111001 y
122 172 07A 1111010 z
123 173 07B 1111011 { (left/opening brace)
124 174 07C 1111100 | (vertical bar)
125 175 07D 1111101 } (right/closing brace)
126 176 07E 1111110 ~ (tilde)
127 177 07F 1111111 DEL (delete)

November 2008 257 OUCS