c++ physics - university of oxfordbrisbane/cpl…  · web view · 2013-12-09the result being 2...

384
C++ for Physics Oxford University Computing Services

Upload: buithien

Post on 21-Mar-2018

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ for Physics

Oxford University

Computing Services

Page 2: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

like this . Drop-down menu options are indicated by the name of the

option enclosed in square brackets, for example File | Print . To select the option Print from the File menu: click with the mouse button on the File menu name; move the cursor to Print; when Print is highlighted, click the mouse button again.

A button to be clicked will look like this . The names of software packages are identified like this, and the

names of files to be used like this .

OUCS ii November 2008

Page 3: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

Software UsedEclipse

Files Used in Session 1These are available from:http://www-pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013/EclipseStudentFiles_part1.tgz Array.cpp InsertionSort.hArray.dev LinearSearch.cppCharNumString.cpp LinearSearch.devCharNumString.dev MultiDimArrayMain.cppCharNumStringFunc.cpp OverLoadingFunctions.cppCharNumStringFunc.dev OverLoadingFunctions.devconstructor.txt PointerArithmetic.devDoWhile.dev PointerArithmeticMain.cppDoWhile.h Pointers.devDoWhilemain.cpp PointersMain.cppFunctionTemplate.dev StudentMarksInterface.hFunctionTemplate-Maximum.cpp StudentUG.txtFunctionTemplate-Maximum.h TemperaturesRetValues.cppGetSet.txt TemperaturesRetValues.devHeader.cpp Vector.cppHeader.dev Vector.devIf.dev Vector.txtIfMain.cpp While.devIfSwitch.cpp While.hIfSwitch.dev WhileMain.cppIfSwitch.h

Revision Information

Version Date Author Changes made1.01.1

26 November 200828 November 2013

Ian MillerSean Brisbane

CreatedUpdated to use Eclipse IDE

CopyrightThe copyright of this document lies with Oxford University Computing Services.

November 2008 iii OUCS

Page 4: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

Contents1 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++............................................................................................................................................................5Exercise 1 Installing Dev-C++.......................................................................................................................6

4.3. Configuring the Eclipse workspace..............................................................................................................12Exercise 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++.....................................................................................................20Exercise 2 Creating a first program.............................................................................................................21

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

5.4. What does this first C++ program do?........................................................................................................26Exercise 3 Modify the program...................................................................................................................28

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

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

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

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

6 INTRODUCTION TO FUNCTIONS........................................................................37

6.1. Creating a function........................................................................................................................................37Exercise 5 Examining a function.................................................................................................................38

OUCS iv November 2008

Page 5: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

6.2. Functions and Pass by Reference.................................................................................................................44Exercise 7 Pass arguments by reference......................................................................................................45

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

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

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

7.3. Data Members................................................................................................................................................50Exercise 10 Using data members...................................................................................................................51Exercise 11 More Objects..............................................................................................................................52

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

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

7.6. Separate Class Files for Reusability.............................................................................................................57Exercise 13 Using header files.......................................................................................................................57

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

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

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

8.3. Repetition – while, do…while and for loops................................................................................................68Exercise 16 while loop...................................................................................................................................68Exercise 17 for loop.......................................................................................................................................72Exercise 18 do…while loop...........................................................................................................................73

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

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

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

9.3. Sorting Arrays with Insertion Sort...............................................................................................................81Exercise 21 Sorting an array..........................................................................................................................81

9.4. Multidimensional Arrays..............................................................................................................................83Exercise 22 Creating a multidimensional array.............................................................................................84

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

November 2008 v OUCS

Page 6: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

10 MORE ON FUNCTIONS.......................................................................................98

10.1. Multiple arguments and default values......................................................................................................98Exercise 27 Functions with multiple arguments and default values..............................................................98

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

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

10.4. Passing Two-dimensional Arrays to Functions.......................................................................................106Exercise 31 Multi-Dimensional Arrays and functions.................................................................................106

10.5. Overloading functions................................................................................................................................109Exercise 32 Function Overloading...............................................................................................................109

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

11 POINTERS.........................................................................................................115

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

11.2. Pointer Arithmetic and Arrays.................................................................................................................117Exercise 35 Pointers and Arrays..................................................................................................................118

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

12.1. Interfaces.....................................................................................................................................................122Exercise 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.........................................................................................126Exercise 37 Examine inline functions and call by reference.......................................................................127

14.3. Reference parameters and classes............................................................................................................130Exercise 38 Examine and modify class reference parameters.....................................................................131

14.4. Constant objects and const member functions........................................................................................132Exercise 39 Modify constant pointers and references.................................................................................134

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

OUCS vi November 2008

Page 7: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

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

15.3. Public, Private or Protected?....................................................................................................................137Exercise 40 Base and Derived classes.........................................................................................................138

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

15.5. Preprocessor wrappper #indef..................................................................................................................144Exercise 42 Add a preprocessor wrapper.....................................................................................................144Exercise 43 Adding an additional class.......................................................................................................145

15.6. Overriding base class methods..................................................................................................................146Exercise 44 Overriding Base Class Methods...............................................................................................146Exercise 45 Human Inheritance...................................................................................................................148

15.7. Friends and Functions...............................................................................................................................150Exercise 46 Examine a friend function........................................................................................................150Exercise 47 Add a friend function...............................................................................................................152

15.8. Friends and Classes....................................................................................................................................153Exercise 48 Using friend classes..................................................................................................................153Exercise 49 Adding a friend class................................................................................................................155

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

16 OPERATOR OVERLOADING............................................................................162

16.1. Overload + operator...................................................................................................................................162Exercise 53 Overloading the addition operator +........................................................................................162

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

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

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

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

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

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

19 POLYMORPHISM..............................................................................................179

19.1. Polymorphism.............................................................................................................................................180

November 2008 vii OUCS

Page 8: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

20 SESSION 3.........................................................................................................187

20.1. files used......................................................................................................................................................187

21 ABSTRACT CLASSES......................................................................................188

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

22 COMPLETING THE OUCS ATM........................................................................197Exercise 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...........................................................................................................................208Exercise 67 Using files to add data to containers........................................................................................210

23.7. Using the vector class container................................................................................................................212Exercise 68 Vectors, iterators and algorithms.............................................................................................213Exercise 69 Calculating the min, max and mean of vector elements..........................................................216

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

23.9. Using the deque class container................................................................................................................225Exercise 71 Using the deque container........................................................................................................226

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

23.11. Using the multimap associative container.............................................................................................234Exercise 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

Page 9: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

Page 10: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

1 IntroductionWelcome 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 [email protected].

1.1. What you should already knowThere 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 3Working with Dev-C++; Inline functions; STLCreating first programs; Call by reference and

value;Iterators

Fundamental data types, strings, casts;

Inheritance; Vector container

Classes and objects; Public, Private and Protected data;

List container

Attributes and behaviours;

Base and derived classes;

Deque container

Member functions; Preprocessor wrapper #indef;

Multiset container

Constructors; Overriding functions; Multimap container

Destructors; Friend functions; AlgorithmsControl Flow Friend classes;Functions Composition;Arrays and Vectors Dynamic memory

allocation and pointers;

November 2013 1 OUCS

Page 11: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Header Files Pointer based string processing;

Interfaces String manipulation functions;Operator overloading;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

Page 12: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

2 Things to understand

2.1. Compilers, new and oldNot 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

Page 13: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 functions that implement operations and data that implements attributes.Real world object and class objects share two characteristics: They both have a state and behaviour . For example, cars have a state (speed, number of wheels, number of seats, colour) and behaviour (moving, stopped, braking, accelerating, slowing down, changing gear). Class objects are modelled after real-world objects so they too have state and behaviour . A software object maintains its state in one or more variables where data is stored. A variable is an item of data named by an identifier. A software object implements its behaviour 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 classes and objects . 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 class then it is possible to instantiate (create) many objects 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 subclasses of the car class. Similarly, the car class is the superclass of Jaguar X-Type, Mazda RX3, Bentley, Ford Focus. Each subclass inherits 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 inherits 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.

Physics/ITLP 4 November 2013

Page 14: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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.

November 2013 5 OUCS

Page 15: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

4 Setting up the environment4.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 source code (a high level language code). The compiler then converts this precise language (C++) into a concise language that the computer can understand called object 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.

Physics/ITLP 6 November 2013

Page 16: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 1 Installing Dev-C++ Install Dev-C++

Task 1Install Dev-C++

Step 1 Using Windows Explorer or My Computer navigate to the H:\ drive and double click on the program devcpp-4.9.9.2_setup.exe , see Figure 1.

Figure 1

Step 2

Click OK when you see the installation window prompt shown in Figure 2.

Figure 2

November 2013 7 OUCS

Page 17: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 3

From the Installer Language window select English (or a language of your choice) then click OK . See Figure 3.

Figure 3

Step 4 Click the I Agree button when you get to the License Agreement window, see Figure 4.

Figure 4

Physics/ITLP 8 November 2013

Page 18: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 5 Click on Next when you see the Choose Components window, see Figure 5.

Figure 5

Step 6 Click the Install button at the Choose Install Location window. See Figure 6.

Figure 6

November 2013 9 OUCS

Page 19: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 7 Click on the Yes button at the prompt shown in Figure 7.

Figure 7

Step 8 To complete the installation click Finish , see Figure 8.

Figure 8

Step 9 At the Beta version Notice click OK , see Figure 9

Figure 9

Physics/ITLP 10 November 2013

Page 20: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 10 When you see the Dev-C++ first time configuration window (Figure 10) click the > Next button.

Figure 10

Step 11 Make sure Yes, I want to use this feature is selected then select the > Next button to select additional features, see Figure 11.

Figure 11

November 2013 11 OUCS

Page 21: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 12 To create the code completion cache click the > Next 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 OK .

Figure 13

Physics/ITLP 12 November 2013

Page 22: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 14 Close the Tip of the day window by clicking the Close 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 projectsMany 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.

November 2013 13 OUCS

Page 23: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 1 Importing project skeletons into eclipse Open eclipse Import projects

Task 1

Launch eclipse

Step 1

OSX machines, select the "launchpad" 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.

Physics/ITLP 14 November 2013

Page 24: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2Choose a workspace Choose a new workspace

We will split the work into three sessions. Name the new workspace "workspace_part1" in the Documents sub directory of your home directory.

Figure 18

Task 3Download the materials for the session from the web. These are currently located at:

Step 1

Download the required materials from the web. These are 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

November 2013 15 OUCS

Page 25: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4Import the first part into your project workspace

Import the project skeletons into your workspaceSelect File=> Import

Figure 19

Physics/ITLP 16 November 2013

Page 26: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 5Select the existing project option

Choose to “import an existing project into the workspace”. Do not select the “Archive File” option.

Figure 20

November 2013 17 OUCS

Page 27: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 6Import the tar file you have just downloaded in Error:Reference source notfound

On the next page, the type is archive file. Browse to the directory of files that you unpacked in Error: Reference source not found. Within that directory is another archive ProjectsSkel.tar.All projects within the archive should automatically be detected and ticked.

Figure 21

Physics/ITLP 18 November 2013

Page 28: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 7 Build and run the project

After editing projects, they should be built and run. Initially, select build project from the project menu.

Figure 22

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

See Error: Reference source not found on the next page

November 2013 19 OUCS

Page 29: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 23

Physics/ITLP 20 November 2013

Page 30: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

5 Creating your first program5.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++

November 2013 21 OUCS

Page 31: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 2 Creating a first program Open Dev-C++ Add a first program

Task 1Create your first program.

Step 1 If Dev-C++ is not already running, open the program by double clicking on the icon in the NAL window or select Start | All Programs | Bloodshed Dev-C++ | Dev-C++ .

Select File | New | project . The dialog box shown in Figure 24 appears.

Figure 24

Select Console Application Add a project the name of WelcomeSelect the C++ Project radio buttonClick OKSave the project to the \ as Welcome.dev see Figure 25

Physics/ITLP 22 November 2013

Page 32: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 25

Dev-C++ creates a basic template source code file you that you can build on. See Figure 26.

Figure 26

November 2013 23 OUCS

Page 33: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

5.3. Creating your first program in eclipseCreating a new project

Exercise 2 Creating a first program in eclipse Open eclipse Add a first program

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

Step 1

Figure 27

Physics/ITLP 24 November 2013

Page 34: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3Create a new empty project

Step 1Select an empty project using the “Mac OSX GCC" toolchain on the Mac or the “Linux GCC toolchain” on Linux

Step 2Give the project the name Hello and accept the default options

Figure 28

November 2013 25 OUCS

Page 35: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4Add a new source file into the projectCall the new source file “HelloWorld.cpp”

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

Figure 29

Task 5Create an initial program to pring “Hello World” to the console.

Copy the following text into your new source file:

#include <cstdlib>

#include <iostream>

using namespace std;

int main (int argc, char* argv[])

{

std::cout << “Hello World” <<std::endl;

return EXIT_SUCCESS;

}

Physics/ITLP 26 November 2013

Page 36: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 6 Build and run the project

After editing projects, they should be built and run. Initially, select build project from the project menu.

Figure 30

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

See Error: Reference source not found in Error: Referencesource not found

5.4. What does this first C++ program do?#include <cstdlib>This statement is a pre-processor directive to include the contents of the header file cstdlib 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.

November 2013 27 OUCS

Page 37: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

#include <iostream>Notifying the pre-processor to include in the program the contents of the header file iostream 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 std tells the compiler to treat the names (members of the namespace std) in the standard library as though we had defined them in the current program. The members we will be using throughout our programs are:cin - is the "standard input stream object" of the namespace std and we must include the header file <iostream> in order to use them (you will be using this in the next exercise). The cin object enables a program to input data from the keyboard or other device.cout - is the “standard output stream object” of the namespace std (you will be using this in the next exercise). The cout object enables a program to output data to the screen or other devicesendl - is a stream manipulator that writes a new line to output. endl stands for end of line and is pronounced “endell”.string - allows us to use the string class (more on classes later) as an alternative to using C style character arrays. "namespaces" 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[]) - main() is part of every C++ program. The parenthesis () after main indicate that main is a program building block called a function . Inside the function parenthesis are arguments passed to the function. They are:

argc - is a count of the arguments supplied to the program of type int (integer). *argv[] 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 argc and *argv[] and the statement int main(int argc, char *argv[]); could be replaced with int main().

return EXIT_SUCCESS; tells the OS the program completed successfully. An alternative way of writing this statement is: return 0;

Physics/ITLP 28 November 2013

Page 38: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 3 Modify the program Prompt the user to enter a number Read in the number Output the number to screen

Task 1Modify the program

Step 1 Add the following statements immediately above the statement return EXIT_SUCCESS;int anum = 0;

cout <<"Enter a number ";

cin >>anum;

cout <<"The number you entered is : " << anum << endl;

Step 2 Save the file as main.cpp

The statement int anum = 0; defines a variable (a memory location) called anum to store a number of type int to hold an integer (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 "; cout is a name that belongs to the "namespace" std . The << is the "stream insertion operator". 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; cin is the "input stream object" of the "namespace" std . >> is the "stream extraction operator" 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.

November 2013 29 OUCS

Page 39: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 2Compile the program

Step 1 Build the projectIf 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 3 Run the program

Step 1 Run the project and select the box in Eclipse labelled “Console” as in Figure 31.Enter a number at the prompt and press Enter

Figure 31

The output is shown in Figure 32.

Figure 32

Physics/ITLP 30 November 2013

Page 40: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 = 215 % 6 = 3The result being 2 remainder 3.

C++ Operation

C++ arithmetic operator

Algebraic expression

C++ expression

Addition + y + 6 y + 6Subtraction - a - b a - bMultiplication * c * d or cd c * dDivision / x/y or or x / y

Modulus % p mod q p % qTable 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 ExampleDouble 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 integer data types. Characters are represented as

November 2013 31 OUCS

Page 41: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

single byte integers in the computer so it is possible to output a character as an integer or as a character.

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 (aChar) 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 statementbInt = 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 Casts .

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 “Oxford” or “St.Andrews”. 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”;

Physics/ITLP 32 November 2013

Page 42: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

string firstName = “Ann”;

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 name. You could create a second string and get the user to enter Black but this is inconvenient. To handle this situation use the getline(cin, name); command instead of cin >> name;. This reads all key strokes into name until the <ENTER> key is pressed. The getline 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: - The length of the string myName is 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

November 2013 33 OUCS

Page 43: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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.

When you need to represent a value as a different type you can use the static_cast notation as shown here:

To change a double to an integer:

int anInt;

anInt = static_cast<int>(doubResult); where doubResult 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 bInt is an integer.

Physics/ITLP 34 November 2013

Page 44: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 1In eclipse, open the project CharNumString and examine the program. Note how the string class has been used together with its member function length() .

Step 1 Examine the program CharNumString.cppThe text at the top of the page starts with a (/*) and ends with (*/). /*This program ……… data types.*/.

This is a block comment and is ignored when the 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 one 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.

November 2013 35 OUCS

Page 45: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 2Create another project, call it Even . Write a program that will read in two numbers of type double and two numbers of type integer . The program should output the sum, the product and the difference of the double numbers. Also output the quotient and the fractional part of the division of the two integers .

Task 3Modify your program in Task 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 ASCII integer values of each character.

Physics/ITLP 36 November 2013

Page 46: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 4Create another project called Address . Write a program that can be used to collect user data. Output this data to screen as shown in Figure 33.

Figure 33

Task 5Create another project call it CalcArea .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.141592a = ∏r2, c= 2∏r, v= ah

November 2013 37 OUCS

Page 47: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 7Create a new project,call it SearchString .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.The string before and after the update should be displayed as in Figure 34.

Figure 34

Physics/ITLP 38 November 2013

Page 48: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

6 Introduction to FunctionsFunctions 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. 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 declared with a prototype early in the program. A function prototype consists of the return type , a function name and a parameter list indicating the data the function will receive. The function prototype is also called the function declaration .The function definition consists of the prototype and a function body, which is a block of code enclosed in parenthesis. Using a prototype 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 definition creates the actual function in memory. Arguments can be passed to functions in two ways. Pass-by-value 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 passed-by-reference . 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 pointers can be used to pass-by-reference.

6.1. Creating a functionThe format of a function prototype is:return_data_type AnyFunctionName (argument_list) The statement void FtoCent(int temp); has no return data type (void), it’s name is FtoCent and it accepts an argument called temp of type int (integer). It is not strictly necessary to give the argument a name (temp) in the prototype. However, the argument type must be specified. The

November 2013 39 OUCS

Page 49: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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.

Physics/ITLP 40 November 2013

Page 50: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 1In eclipse, open the project CharNumStringFunc

Step 1 Compile the program, sorting any compilation errors.Run the program entering the data as requested. The 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 prototypes in this program. Creating prototypes allows the compiler to perform type 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 void .

November 2013 41 OUCS

Page 51: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

void passReadChar(int); function prototype. This function receives an argument of type int (integer) and returns no values.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 (void).

Calling functions:readChar(); This is a function call to the readChar() 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 passReadChar() 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.

Physics/ITLP 42 November 2013

Page 52: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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.

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 length() . This is returned to the calling statement. void readDouble()

{

static int aNum = 1;

aNum +=1;

}

Note here the use of the keyword static. This has defined the memory location aNum 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 static 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 added to the variable aNum .

November 2013 43 OUCS

Page 53: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 2Remove the key word static from the declaration static int aNum = 1; this is in the void readDouble() function. Compile and run the program and see how the program responds.

Physics/ITLP 44 November 2013

Page 54: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 1Open the project Even you created in Section 4, Exercise 4 and change the structure of the program to make use of functions.

Step 1 Read two integers in to main() and pass them to a function. The prototype is void intCalcs(int, int); intCalcs() function should calculate and display the result of the division and modulus of the two variables passed, see Figure 36.Read in two doubles to variables in main(). Pass the two doubles and the value of one integer to the second function, the prototype is int Calcs(double, double, int); Within function Calcs() write statements to produce the output as shown in Figure 36. Most of the code already exists within main(). Return the result of the multiplication of one double and an integer, cast this value as an integer. Display the returned value within main(), as shown in the second last line in Figure 36.

Figure 36

November 2013 45 OUCS

Page 55: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

Physics/ITLP 46 November 2013

Page 56: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3 Create a new project,call it ChurchHeight . Write a program that will calculate the height of a building given the following information.You are 270 metres away from a church. The angle from your feet to the top of the church is 16 degrees, see Figure 37 and Figure 38.The height of the 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 the angle to radians before using the cmath function tan(x) . See Appendix 24.15 for more information on cmath functions.

Remember to include the header file <cmath> in your program.

Figure 37

Figure 38

November 2013 47 OUCS

Page 57: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4 Create a new project,call it Metres .Write a function named FItoMeters 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 Seconds .Two identical experiments have been conducted and the time difference between the two (in seconds) is critical. Write a function (HMSeconds) 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.

Physics/ITLP 48 November 2013

Page 58: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 main(). The arguments were passed by their value .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 (main() 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 value-arguments cannot change the variable passed from main() because any changes only apply to local copies in the function, not the actual caller's variables.Passing variables to functions by reference 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 const and pass them by reference.The format of a function prototype when using call by reference is:return-data-type function-name (reference parameter). To indicate a reference parameter, an ampersand (&) is written in the function prototype and header after the parameter type name The statement void squared(int &); has no return data type (void), it’s name is squared and it accepts a reference parameter (&) of type int (integer).

The function definition would be: squared(int & inVal)

{

inVal = inVal * inVal;

}

The function call would be:squared(aValue); where aValue is a reference to an integer value

stored in the memory location defined as aValue . The address in memory of aValue is passed to the function squared, not the value.

November 2013 49 OUCS

Page 59: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 7 Pass arguments by reference Examine how parameters can be passed by reference Create functions using parameters passed by reference

Task 1In eclipse, open the project FunctionRef

Step 1 Compile and run the program. The output should be the same as shown in Figure 39.

Figure 39

Examine the function prototype:void squared(int &);This shows the function squared accepts a reference parameter of type int. The reference parameter is the memory address of the argument passed to the function.The function uses this address to both get and set the value stored in variable a, (21) in main(). A reference to this address is passed to the function with the function call squared(a);

Step 2 Examine the function void squared(int &x)x refers to the address of (a) in main, that holds the number 21 .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, main() in this example.

Physics/ITLP 50 November 2013

Page 60: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2 Create another project call it FuncRefMarks . 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 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 main() function. The output should be similar to that shown in Figure 40.

Figure 40

November 2013 51 OUCS

Page 61: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 3 Open the file FuncConstRef 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 output should be as shown in Figure 41.

Figure 41

Physics/ITLP 52 November 2013

Page 62: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 attributes, 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 behaviours 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, object.memberfunctionname(). An example is student1.getName() . The object is student1 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 main() 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 53 OUCS

Page 63: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

7.1. Creating your first class

Exercise 8 Creating a class Create a class Create an object of the class

Task 1Create a new project,call it Student . Name the new source file StudentUG.cpp . From the directory where you unpacked the source materials, open the file called StudentUG.txt . Copy the C++ program. Replace the default C++ template file (StudentUG.cpp) with the file copied from StudentUG.txt . The program should look like Figure 42. Compile and run the program.

Figure 42

Before you can create the object myName 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 */

Physics/ITLP 54 November 2013

Page 64: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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

}; /*end of class definition. *//*Note: a semicolon is required at the end of the class definition*/Within main() the statement StudentUG myName; creates the object myName of class StudentUG.

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

As we have seen previously the function main() is called automatically when our programs are executed. However, member functions (displayname() is one, we could have many) must be called in this way, objectName.functionName() .

The member function displayName() 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 int displayName() .

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 studentUG class the calling statement in main() would be:myName.displayName(name); where name is a string (a series of characters) that contains a value read in from the keyboard.

In order for the function displayName() to recognise the parameter being passed the function declaration is changed to include the parameter (name) and type (string) as shown in Figure 43.

Figure 43

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

November 2013 55 OUCS

Page 65: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Physics/ITLP 56 November 2013

Page 66: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

7.2. Member functions and Passing parameters

Exercise 9 Passing parameters Function calls with parameters

Task 1Modify the program you created in the previous exercise StudentUG.cpp 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++ programming. The output should be similar to Figure 44.

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 objects (instances) of the class.

7.3. Data MembersIn all the programs written so far, the variables have been declared inside the main() 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 courseName might be one of several attributes of a Student object. Attributes are represented as variables in a class definition . These variables are called data members and must be declared inside the class definition. When you create an object of a Student class each object has a unique memory location for its data members.Figure 45 shows data member studName declared in the class definition. The access specifier private means that only member

November 2013 57 OUCS

Page 67: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

functions of the class in which the attribute was declared can use this data member.

Figure 45

When data members are declared as private the data is hidden. This is called encapsulation 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 member function to set the data member to a value and create a second member function to output the value held there.Data members can also be declared public. A data member that is declared public can be accessed from any (non-member) function.A protected 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.

Physics/ITLP 58 November 2013

Page 68: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 10Using data members Setting a data member Getting a data member

Task 1Create a new project, call it StudentGetSet . Create a new source file call it StudentCourse.cpp . From the directory where you unpackedthe source materials, open the file called GetSet.txt.Copy the C++ program. Replace the default C++ template file (StudentCourse.cpp) 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.

Figure 46

Task 2Examine the member function returnName() shown in Figure 47. This function produces the output but what does getName() do?

Figure 47

November 2013 59 OUCS

Page 69: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 3Modify the StudentCourse 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. You will need to create additional data members and member functions to achieve this.The output should be similar to Figure 48.

Figure 48

Exercise 11More Objects Creating a second object

Task 1So far you have created one StudentCourse object. It is about time we had a second student on the course. Create a second object of the class StudentCourse . You will need to add the second statement shown in Figure 49 to add the new object yourName . Call the member functions passing parameters as necessary.

Figure 49

7.4. ConstructorsWhen you create objects from the StudentCourse 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 courseName data member (it is possible to initialise some or all of the data members) when each object is created. A constructor is a special kind of function that must have the same name as the class. Constructors are normally defined as public and

Physics/ITLP 60 November 2013

Page 70: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

never have a return type. They can be used to automatically initialise data members. In previous programs you have written, a default constructor 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 overloaded. 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 61 OUCS

Page 71: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 12Using constructors Create a new file using constructors Add a third constructor

Task 1Create a new project, call it Constructor . Create a new source file call it Constructor.cpp . From the directory where you unpackedthe source materials, open the file called constructor.txt . Copy the C++ program. Replace the default C++ template file Constructor.cpp 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.

Figure 50

Task 2In the constructor shown in Figure 51 what does the statement setCourseName(name); do?

Figure 51

Physics/ITLP 62 November 2013

Page 72: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3Create a third constructor that will take arguments of years and enrolDate . Add a third object, call it student3. Write a statement that will output the results of a call to this additional constructor.

Task 4 Each student has an ID number and a supervisor . Modify the program to allow student ID’s and the names of supervisors to be added to each object created. Create member functions to allow the user to add or modify both the ID and supervisor names . Create member functions to output these details to screen.

7.5. DestructorsBoth 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

November 2013 63 OUCS

Page 73: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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:  

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 64 November 2013

Page 74: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

7.6. Separate Class Files for ReusabilityThe programs you have created so far consist of one .cpp source code file that contains a class definition and a main() 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 main() function. As things are, if you include an existing class file in a new program you will also be including a main() function. As there can only be one main() 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 13Using header files Open an existing project Create a header file Use the pre-processor directive

Task 1Open an existing project. Create a header file and include reference to this in the source code file. When main() is called the class definition in the header file is used to create objects of the class defined in the header file.

Step 1 In eclipse, open the project HeaderAdd a new Source file to the project, File | New | Source File Save and name the file OxStudents.h in the same folder as Header .

Step 2 Cut the class definition code from Header.cpp file and paste it into the OxStudents.h file.As you will be using input and output in the class header file you need to include the iostream library. Add #include <iostream>, #include <string> and using namespace std; to the top of the header file.

November 2013 65 OUCS

Page 75: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 3 Compile the programYou should get a compilation error at line OxStudents myName; This is because main() does not know about the header file containing the class information.

Step 4 Add the statement #include "OxStudents.h" beneath the other #include directives in Header.cpp file.Compile and run the programThe statement #include "OxStudents.h" instructs the C++ pre-processor to replace the directive with a copy of the contents of OxStudents.h before the program is compiled.With the OxStudents 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 main(). Note: 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.5Note: 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.

Physics/ITLP 66 November 2013

Page 76: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2Create another project call it Country . Modify the main() source code to use the class in the header file #include "OxStudents.h" . Note: the Oxstudents.h file will need to be copied to the Country 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.

Figure 52

Task 3 Open the project Constructor 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 67 OUCS

Page 77: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4OPTIONAL Create a new project, call it Employees .From the directory where you unpackedthe source materials, open the file called Employees.txtReplace the default file in the project with Employees.txt . Create a header file, call it employee.h . Add two constructors, one default and another to accept the parameters being passed from main(). 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 Figure53.

Figure 53

Physics/ITLP 68 November 2013

Page 78: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

8 Basic Control FlowThe 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:

Sequence statement - the computer executes the statements one after another. All the programs you have written so far use sequence statements.Selection statements - if, if…else, switch.

The if selection statement selects an action if a condition is true or skips the action if false. The if...else selection statement selects an action if a condition is true or performs a different action if the condition is false.The switch multiple selection statement can be used to perform many different actions based on a character or integer value.

Repetition statements - while, for, do…while.The while and the for statements perform actions within their bodies zero or more times depending. If the loop condition test is initially false no actions will occur. The do…while statement will perform the actions in the body at least once.

8.1. Selection - if…else statementThe 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 (mark >=50) is true the statement following it is executed cout << "Passed";

November 2013 69 OUCS

Page 79: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

If the condition is false the statement is ignored and control is passed to the else part of the selection, and statement following else is then executed cout << "Failed"; if…else selection statements can also be nested within other if…else selection statements.

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

Task 1In eclipse, open the project If. There is one .cpp file and one .h header file.

Step 1 Compile the program, sorting any compilation errors.Run the program. The output should be the same as Figure 54.

Figure 54

Physics/ITLP 70 November 2013

Page 80: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Examine the void getGrades() member function in the StudentMarksInterface.h file. The if single selection statement performs only one action when the condition tested (Exam1 >= 90) is true.if(Exam1 >= 90) cout<< "the Exam1 grade is 'A'" <<endl;

The if selection statement returns true only when Exam1 is greater than or equal to 90 . The output is "the Exam1 grade is 'A'". There is no mechanism for testing for other scores with the single if selection statement and the program will continue with the next statement in the program.

Note: >= is a relational operator (greater than or equal to). For more information on relational operators see Appendix 24.4 Relational and Equality Operators.

November 2013 71 OUCS

Page 81: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

To test for, and provide actions for two distinct conditions we can use the if…else selection statement. It is necessary to specify an action when a condition is true (Exam1>=90) and an alternate action when the condition is false .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 if…else 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 getGrades() member function.

Physics/ITLP 72 November 2013

Page 82: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2A 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 screen. They should look similar to Figure56.

Figure 56

8.2. Selection - switch multiple selection statementThe switch 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:

OK – Test is 1, a constant and an integer NOT OK – Test is not constant integer

November 2013 73 OUCS

Page 83: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

Task 1In eclipse, open the project IfSwitch . There are two files, one .cpp files and one .h header file.

Compile the program, sorting any compilation errors.Run the program. The output should be the same as Figure 57.

Figure 57

Physics/ITLP 74 November 2013

Page 84: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2To see how the switch statement gets its parameters and to understand how characters can be used in a switch statement.

Step 1 Examine the void getGrades() member function in the StudentMarksInterface.h file, see Figure 58.

The use of the if statement was explained in the last exercise. The statement countGrades (‘A’) is new. It is calling the function countGrades 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 75 OUCS

Page 85: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Exam the code in countGrades 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 case labels and a default case statement. In Figure 59 these are used to increment the different counters (aCount…fCount) depending on the value of parameter passed. If there is no match between the letter (the controlling expression) and the case labels the default case statement executes.

Physics/ITLP 76 November 2013

Page 86: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3Exam how the count of grades is output.

Step 1 Examine the member function outPutGrades() shown in Figure 60

Figure 60

This member function outputs the object member variables aCount...fCount . The statement student1.outPutGrades(); in main() is used to call the member function and output the total of each grade achieved by the object student1.

November 2013 77 OUCS

Page 87: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4 Create a new project, call it ElectronicsOutlet . You sell the following four products at the unit price shown. Product 1:Astable multivibrators @£15.45Product 2:Integrated-Circuit Timers @ £21.78.Product 3:ECL @£15.78.Product 4:BiCMOS digital circuits @£34.99.

Step 1 Write a program that reads a product ID (Product 1-4) and the quantity required. A switch statement should be used to determine the product sold.Items that are sold in quantities >99 units are reduced in price by 10% before tax is applied.The output should show the cost per item, the VAT element and the total cost including VAT at 17.5% as shown in Figure 61.

Figure 61

Note: 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.

8.3. Repetition – while, do…while and for loopsThe 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)

statementThis can be read as, while the condition is true continue to do the statements until the condition is false.

Physics/ITLP 78 November 2013

Page 88: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 16while loop In eclipse, open the project While Examine how the while repetition statement works Modify the program

Task 1In eclipse, open the project While . There is one .cpp file and one .h header file.

Step 1 Compile the program, sorting any compilation errors.Run the program. The output should be the same as Figure 62.

Figure 62

November 2013 79 OUCS

Page 89: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Open the while.h file and examine the member function getStudentDetails(). The condition tested in this loop is the counter value. The statement while (counter <= 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 false and terminate the loop, the counter value has to be incremented (it could be decremented depending on design). The statement counter ++; achieves this, incrementing counter by 1. For more detail on incrementing variables see Appendix 24.3.Note: 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 2Modify 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. Note: you will need to use a method of selection to establish the highest and lowest marks inside the while loop.

Physics/ITLP 80 November 2013

Page 90: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3 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, 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.

Figure 63 BMI Calculator

November 2013 81 OUCS

Page 91: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4OPTIONAL 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.

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.

Figure 64

Physics/ITLP 82 November 2013

Page 92: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 5OPTIONAL 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 PIN numbers.

Figure 65

Exercise 17for loop Modify the program using the for loop

Task 1Modify the program in Exercise 14 Task 2 to use the for loop. You will need to modify the code in student.h .The code you need to add is shown in Figure 66.Note: The for loop is a special kind of while loop.

The format of the for loop is:for (i = start; i <= end; i++){Statements;}In the above piece of code it is assumed i is declared as a variable in the declarations section within the program.

Figure 66

Figure 66 shows the code required to read in four exam marks. Note: The integer i used to control the loop and has been declared within the brackets of the for loop (int i = 0;). This means that i only exists within the loop. When the loop ends, i ceases to exist. This is called the scope of the identifier. See appendix Scope 24.10 for more information.

November 2013 83 OUCS

Page 93: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 2OPTIONAL Create a new project, call it Books .The program should create three instances of a class called Books . Create each of the objects inside a for loop . Create member functions to add a Title, Author and date of publication.Output the details of the three books to screen.

Physics/ITLP 84 November 2013

Page 94: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 18do…while loop Understand the difference in while and do…while loops

Task 1Note: You should complete the chapter on classes before attempting this task.In eclipse, open the project DoWhile . Establish how the do…while loop can effect a program written to verify user input.

Step 1 Open DoWhile projectRun the program entering the numbers 19, -19, 19, -19 when promptedThe output of the program is shown in Figure 67.

Figure 67

Establish why when using the do…while loop for repetition a negative value (-19 as shown in Figure 67) is established as being greater than zero. Hint: Look at where in the block the condition is tested.

Task 2Note, you do not need the classes chapter to attempt this exercise.Create a new project, call it Factorial Using different repetition statements write a program to calculate and display the factorial of a value entered by the user. See Figure 68.The factorial of '6' is 1*2*3*4*5*6 = 720.

Figure 68

November 2013 85 OUCS

Page 95: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Physics/ITLP 86 November 2013

Page 96: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

9 Arrays, vectors and listsArrays, 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, vector and list 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 arraysArrays are declared indicating the type and number of elements in the following way:type arrayName[arraySize]Examples are:int inNumbers[20]; an array called inNumbers of 20 integers.char inName [20]; an array called inName of 20 characters.

November 2013 87 OUCS

Page 97: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

float ExamMarks[5] = {0}; an array called ExamMarks of 5 float with all elements explicitly initialised to zero.

const int size = 5; declaring a constant variable size . float ExamMarks[size]; When the constant variable size 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 size changes the number of elements wherever the ExamMarks array is used in the program. int numArray [2] [3] is a multidimensional array with 2 rows and 3 columns.

Note: 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.

Physics/ITLP 88 November 2013

Page 98: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 19Creating an array to hold exam results Open project Array Examine how values are written into the array Modify the program to read in 10 exam marks

Task 1In eclipse, open the project Array

Compile the program, sorting any compilation errors.Run the program adding five exam results. The output should be similar to Figure 69.

Figure 69

November 2013 89 OUCS

Page 99: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 1 Examine the following statements double ExamMarks[5] = {0}; This statement declares the array, setting it’s size to 5 elements and explicitly initialising all elements to zero.cout<<"Enter Exam Mark "<<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 Exam Mark 1 not exam mark 0 which would be less intuitive.Array elements are numbered from 0 to n-1. So an array that holds 20 integers will be addressed from element 0 to 19.ExamMarks[0]…ExamMarks[19]The first number will be entered into element [0] . The last into element [19] .cin>>ExamMarks[i];This statement reads in the user input and stores the values in the array elements of ExamMarks[i] . i is incremented within the for loop and starts at 0.

Task 2Modify the program to calculate the highest and lowest numbers in the array.

Physics/ITLP 90 November 2013

Page 100: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3Create another project call it Names . 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).One member function is length(). 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.

Figure 70

November 2013 91 OUCS

Page 101: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4OPTIONAL Create another project call it ArrayNameAge. 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 shown in Figure 71.Modify the program to establish the average age. Output the result.

Figure 71

Physics/ITLP 92 November 2013

Page 102: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

9.2. Searching Arrays with Linear SearchLinear 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 20Linear 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 1In eclipse, open the project LinearSearch

Step 1 Compile the program, sorting any compilation errors.Run the program; choose a number between 1 and 100 . The output should be similar to Figure 76.

Figure 72

November 2013 93 OUCS

Page 103: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Examine the following statements myArray[i] = (1 + rand()%100); This statement uses the rand function, part of the <cstdlib> header file. rand()%100 produces integers in the range 0 to 99.The function linearSearch 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 main() otherwise -1 is returned. The if selection statement if (element != -1 ) in main() is used select the output indicating a successful or unsuccessful search.

Task 2Create another program to output a count of the individual numbers held in an array. The numbers in the array should be randomly generated. The output should be as shown in Figure 73.

Step 1 Create a project, call it SearchCountValCreate a new source file SearchCountVal.cpp Create a header file SearchCountVal.h

Step 2 Write the program, creating an array of random numbers. Create a small array of 15 elements and add random numbers to the array using the rand function. The random numbers should be between 0 and 14 .You will need to #include <cstdlib> for rand()

Step 3 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.

Physics/ITLP 94 November 2013

Page 104: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 4 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 73The 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

November 2013 95 OUCS

Page 105: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

9.3. Sorting Arrays with Insertion SortWhen 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 21Sorting an array Create a new project, call it InsertionSortClass Add a header file to the project Examine how an array is sorted Modify the program, creating a source file to use the class

informationNote: Please attempt task 1 and 2 after completing the chapter on classesOPTIONAL

Task 1Create a new project, call it InsertionSortClass

Step 1 From the directory where you unpackedthe source materials, open the file called InsertionSort.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() programThe sort works by first looking at array elements sort[0] and sort[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 sort[2] and compares this to sort[1] . If the value in sort[1] is greater than the value in sort[2] the values are swapped. The while loop is then used to compare the value in sort[1] to the value in sort[0] .This iterative process continues until all array elements have been sorted.

Physics/ITLP 96 November 2013

Page 106: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2OPTIONALAdd a new source file to the project call it InsertionSort.cpp

Step 1 Add #include "InsertionSort.h" Create an instance of the class SortArray myArray;Create an array of 200 randomly generated numbers, numbers[i] = (1 + rand()%100);

November 2013 97 OUCS

Page 107: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 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 98 November 2013

Page 108: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3 Create a second object, call it yourArray . 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 ArraysMultidimensional 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 2Row 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.57Row 1 12.76 91.32 27.89

Table 4

November 2013 99 OUCS

Page 109: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 22Creating 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 1In eclipse, open the project MultiDimArrayThere is one associated file MultiDimArrayMain.cpp

Step 1 Compile the program, sorting any compilation errors.Run the program adding 2 exam results for each of the two students. The output should be similar to Figure 76.

Figure 76

Task 2Examine the code used to write values to and read from a multidimensional array.

Step 1 Examine the following code segmentsdouble ExamMarks[2][2] = {0}; This statement creates a two-dimensional array having two rows and 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 .Note: multidimensional arrays can have two or more dimensions (subscripts). Three-dimensional arrays are uncommon.

Column 0 Column 1Row 0 a[0] [0] a[0] [1]Row 1 a[1] [0] a[1] [1]

Table 5

Physics/ITLP 100 November 2013

Page 110: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Examine the following code segment used to read values in to the arrayfor(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 for loops work taking one row at a time (the outer for loop) and looping through the columns in that row (the inner for 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 2Stud 1 67 71Stud 2 61 58

Table 6

Step 3 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 101 OUCS

Page 111: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 3Modify 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 4 Create a new project, call it MatrixManipulation . This program will manipulate a matrix of integers. Each row of 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

Step 1 A multi-dimensional array has been created and initialised with 80 integers. From the directory where you unpacked the source materials, open the file called matrix.txt . Add this to your program.The output from the program should be the same as shown in Figure 77.

Figure 77

Physics/ITLP 102 November 2013

Page 112: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

9.5. Declaring and using vectorsVectors 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 inNumbers with no initial size to hold doubles .vector<char> Name(20); a vector called Name with an initial size 20 to hold characters.vector<int> ExamMarks(4,6); a vector called ExamMarks holding integers with initial size of 4 elements each with the value 6 Note: In previous exercises you have created your own member functions. In the following exercises you will use some of the vector class member functions found in the Standard Template Library (STL). Some of these are begin() , end() , erase() , and size(). See section 24.13 for more detail.The STL also includes a large collection of algorithms 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 (vec) for example, by using the sort algorithm.sort(vec.begin(), vec.end());

You can find a value (69) in a vector by using the find algorithm.ptr = find(vec.begin(), vec.end(), 69); ptr 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 reverse algorithm.reverse(vec.begin(), vec.end());

There are two important points to notice about the call to reverse . First, it is a global function (as are find and sort) 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 begin() to end() (vec.begin() to vec.end()). reverse , like the

November 2013 103 OUCS

Page 113: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

other STL algorithms, is decoupled from the STL container classes. The reverse algorithm can be used to reverse elements in vectors , in lists (another container), and even elements in C arrays .

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 iterators , 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.

Physics/ITLP 104 November 2013

Page 114: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 23Creating 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 1In eclipse, open the project VectorDemoThere is one associated file VectorDemo.cpp .

Step 1 Compile the program, sorting any compilation errors.Run the program adding five exam results. The output should be similar to Figure 78.

Figure 78

November 2013 105 OUCS

Page 115: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Examine the following statements #include <vector>; This statement includes the header file <vector> enabling the program to use the class template vector. (templates allow the use of generic functions that admit any data type as parameters and return a value, more on this later.). vector <double> ExamMarks (5); This statement declares the vector to hold doubles and sets the initial size to 5 elements. Note: 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.cin>>ExamMarks[i]; This statement reads in the user input and stores the values in the vector slot i of ExamMarks[i]. i is incremented within the for loop in a similar way as in the previous array exercises using the subscript operator [ ].

Task 2From the directory where you unpacked the source materials, open the file called Vector.txt . Copy the code and add it to Vector.cpp

Step 1 Copy the code from Vector.txt and add it to Vector.cpp immediately above the return statement ;Run the program entering 5 numbers. Follow the prompts and add an additional number to the vector. The output should be as shown in Figure 79.Examine the following statement ExamMarks.push_back(test); push_back() 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.

Physics/ITLP 106 November 2013

Page 116: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 79

size() is a member function of the vector class. It can be used to establish the size of a vector. The statement for(int i = 0; i < ExamMarks.size(); i++) uses the vector member function size() available to the vector ExamMarks 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 for loop.

Task 3Modify the program to delete the last element and output the vector slots showing all values. pop_back() is the member function that can be used to delete the last element in a vector.

November 2013 107 OUCS

Page 117: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4 Create a new project, call it VectorSort .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 108 November 2013

Page 118: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 24Create 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 1Create a new project, call it VectorofPenguins .Create a header file Penguins.h and add member functions to allow the user to add and change the penguin type and colour.Add the necessary constructors and destructors including a default constructor that will name a type as "King" with a colour "Black, Grey & Orange" when called. You will need data members to store these values.In main() add a vector to store each object instantiated. Add two objects using code similar to that shown in step 1 then add another penguin object using vector member functions.Output the contents of the vector to screen, it should be similar to Figure 80.

Step 1 In main() create a vector of penguin objects:vector<Penguins> myPenguin(2);

Print out the default contents of the vectorLoop through the vector adding two objectsfor(int b = 0; b < 2; b++)

{

//Read in the penguin type and colour

/*create first object*/

myPenguin[b] = Penguins(name, colour);

}

Figure 80

Object member functions can be accessed using the following notation.

cout<<myPenguin[a].getName()

November 2013 109 OUCS

Page 119: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 25Using 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

Physics/ITLP 110 November 2013

Page 120: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 1Open Insert .Only parts of the program are explained as much of the program has been covered in previous exercises. Important areas of the program are explained in the steps.

Step 1 Examine the code shown in Figure 81

Figure 81This statement creates an iterator that is used to access members of the vector.Iterators are used to access members of the container classes (the container type vector in this case), and can be used in a similar manner to pointers (see Sec 11).

In the example shown in Figure 83, iterator it is used with the insert() function to place the value (200) at the beginning of the vector nums .

Examine the code shown in Figure 82

Figure 82

This statement uses the vector member function begin() to initialise the iterator it with the address of the start of the vector.Examine the code shown in Figure 83

Figure 83

This statement uses the member function insert() and iterator it to insert 200 at the beginning of the vector (it). Note that an iterator is returned by the function insert() that points to the newly inserted element.

November 2013 111 OUCS

Page 121: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Examine the code shown in Figure 84

Figure 84

This version of the insert() 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 (numsTwo) into nums . The three parameters are: (copy to nums+1, from start of numsTwo, to end of numsTwo)

Step 3 Examine the code shown in Figure 85

Figure 85

This version of the insert() function takes 2 arguments. The iterator it + 2 points to element number three. it points to the beginning of the vector and the 2 moves two elements in. The value 696 is inserted at that element.

Physics/ITLP 112 November 2013

Page 122: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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.

Task 2 Add the code shown in Figure 87 to the program and using the insert() member function add the array to the nums vector. Output the contents of the nums vector to screen.

Figure 87

9.6. Declaring and using listsLists 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.lists 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.

November 2013 113 OUCS

Page 123: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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 inNumbers with no initial size to hold doubles .list<char> Name(20); a vector called Name with an initial size 20 to

hold characters.list<int> ExamMarks(4,6); a vector called ExamMarks holding integers with initial size of 4 elements each with the value 6

Note: In the following exercises you will use some of the list class member functions found in the Standard Template Library (STL). Some of these are begin() , end() , sort() , and swap(). The STL also includes a large collection of algorithms that manipulate the data stored in lists. See section 24.14 for more detail.

Physics/ITLP 114 November 2013

Page 124: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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

Task 1In eclipse, open the project Merge, and examine the program works.

Step 1 Examine the statement shown in Figure 88

Figure 88

This statement creates two lists to hold doubles, listOne and listTwo .

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.

Step 2 Examine the statement shown in Figure 90

Figure 90

This statement creates an iterator for looping through lists. The iterator type for a list is bidirectional. Note that the iterator type for a vector is random access.The twelve statements following the iterator declaration use the class member function push_back() to add new elements at the end of each list. The push_back member function is common to vectors and lists.

November 2013 115 OUCS

Page 125: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 3 Examine the statement shown in Figure 91

Figure 91

This statement uses member function sort() 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 listOne.sort() provided.

Step 4 Examine the following statements

Figure 92

list iterator it is used to loop through the elements of the list. listOne.begin() returns an iterator to the beginning of the list.listOne.end() returns and iterator to the end of the list. it and the dereference operator * are used to output the values in the vector, *it .

Step 5 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. NOTE: This empties the second and increases the size of first list.

Physics/ITLP 116 November 2013

Page 126: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2 In this task you are asked to examine mainMerge.cpp which copies the contents of listTwo to listThree . Note that copy is an algorithm not a member function of the list class.

Step 1 The listThree obnect is resized to to the same size as listTwo using the list member function resize() so that the list can hold all the elements copied. Arguments to resize are the size of listTwo . The listTwo member function size() is used to get this value.Copy the contents of listTwo to listThreeThe syntax for the copy algorithm is: iterator copy( iterator start, iterator end, iterator destination );The return value ‘iterator’ is an iterator to the destination of the last element copied.

November 2013 117 OUCS

Page 127: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

10 More on FunctionsFunctions 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.

Physics/ITLP 118 November 2013

Page 128: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 27Functions with multiple arguments and default values

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

Task 1Create a new project, call it Salary. Name the source file Salary.cpp . The program should read in a gross salary and rate of Income Tax (IT). The salary, IT and National Insurance rate (NI) will be passed to a function to calculate and display the take home pay. Take home pay is calculated as follows: TakeHomePay = (grosspay*(1-NI))*(1-Income Tax)

Step 1 The function prototype you create should be similar to void CalcSalary(double grossSal, double IT, double NI = 5.0); Note: In this prototype we are passing multiple arguments. Each argument is separated by a comma. A default argument double NI = 5.0 has been also used in the prototype above. Default arguments must be declared at the end of the list of arguments. Because we are using a default argument for the national insurance rate it is only necessary to read in a gross salary and the rate of income tax. Gross salary and income tax are passed to the function from main() in the statement CalcSalary(grossSal, IT); along with the default NI argument specified in the prototype. All three arguments are used in the function to calculate the take home pay.Remember, default arguments must be declared at the end of the list.

November 2013 119 OUCS

Page 129: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

IT 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 2Modify the program Salary.cpp to read in the gross salaries of five members of staff. Calculate the take home pay and display.

Task 3ONLY ATTEMT THIS IF YOU HAVE COMPLETED CHAPTER 7Create an object for each member of staff.Create separate member functions to change the rate of NI and Income Tax .

10.2. Returning values from functionsOne 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.

Physics/ITLP 120 November 2013

Page 130: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Returning values in this way allows the reuse of the function and calculations contained in it.

Exercise 28Returning a value from a function Examine and understand how to return values from a function Modify an existing program Create additional projects

Task 1In eclipse, open the project TemperaturesRetValues and modify the program.

Step 1 Run the program. The output should be the same as shown in Figure 94.

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 FtoCent() passes arguments I_far 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) {}

November 2013 121 OUCS

Page 131: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 5 Examine the function body. The two statements below convert the temperature input. The conversion type required is identified using the user input ind and if selection.The statement I_far = (ITemp - 32) *5 / 9; is used to calculate the temp in centigradeThe statement I_far = static_cast<int>(ITemp * 1.8 + 32); is used to calculate the temp in farenheit.The last statement in the function is return I_far; This statement returns the temperature I_far to the calling statement in main().Note: The data being returned must be the same data type as defined in the function prototype. In this example an integer.

Task 2(REQUIRES COMPLETION OF 27)Open the Salary project you created in Exercise 27 Functions with multiple arguments and default values.

Step 1 Modify the program so take home pay is returned from the function and output to screen from within main() . If you completed Task 2, you will need to add a member function of the class to achieve this.

Task 3OPTIONAL 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.

Physics/ITLP 122 November 2013

Page 132: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

November 2013 123 OUCS

Page 133: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 29Classes and functionsOPTIONAL

Create a class file to calculate the average of results

Task 1Open the project you created in the last task, ReturnExperResults, Exercise 28 Task 3.Create a class call it Experimentresults in a new file called ReturnExpResults.h. The values read in to main() 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 main() from the function readNumbers( ), then output to screen.

Physics/ITLP 124 November 2013

Page 134: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

November 2013 125 OUCS

Page 135: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

10.3. Passing Arrays to FunctionsTo 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 30Passing 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 1Create a new project,call it ArrayReturnValue . Pass an array to a function and read in five numbers. Calculate the average value in the array, return this to main() and output to screen.At the end of the program output the values in the array from within main().

Step 1 Create a new project, call it call it ArrayReturnValue Create a function prototype double calcAverage(double ExamMarks[], int num); ExamMarks[] is the array being passed. As with passing variables, it is not strictly necessary to pass the name of the argument, just its type. This could have been written as calcAverage(double [], int num); However, it is useful for future reference as it helps explain how the function works.It is also necessary to pass the size of the array. num is the number of elements in the array, it’s size.

Step 2 Within main() declare the array and initialise the elements to zero with the following statement double ExamMarks[5] = {0}; This declaration explicitly initialises the first element to zero and implicitly initialises the remaining four to zero

Physics/ITLP 126 November 2013

Page 136: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 Create a function double calcAverage (double ExamMarks[], int num) { } Read in the values and calculate the averageAdd the code to establish the average of values in the arrayReturn the average value to main() and output

Step 4 Call the function from within main() with the following statementaverage = calcAverage(ExamMarks, 5);

Step 5 At the end of main() 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 main() all the values in the array entered within the functionIn previous exercises when parameters (variables) were passed to functions the function received a value . When a value 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 value in it are lost. However, the array in this exercise was initialised in main() with zeros and then passed to the function. Data was then added to the array and calculations done. At the end of main() the values in the array elements are output. The array contains values input from within the function.When the function is called calcAverage(ExamMarks, 5) the name of the array, ExamMarks is passed.

November 2013 127 OUCS

Page 137: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

The name of the array is the address 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 (references) any changes made to array elements in the function affect the memory location set up in main() for the array. C++ passes arrays to functions by reference (to the memory location of the first element). In previous exercises functions were passed values , copies of the variables in main().

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

Physics/ITLP 128 November 2013

Page 138: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 3 Go back to Exercise 21 and modify the header file to sort the array passed using the global vector function sort().You should be able to replace the whole member function functionality with one statement.Note that you will have to change the class member function name from sort 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() .

Task 4 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.

November 2013 129 OUCS

Page 139: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

10.4. Passing Two-dimensional Arrays to FunctionsIt 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.728712.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 Balance array in the statement above has two rows and three columns.

Physics/ITLP 130 November 2013

Page 140: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 31Multi-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 1Create 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 131 OUCS

Page 141: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

The output to screen will show the total sum invested, the interest accrued and the balance after addition of interest for each customer.The last line of output will show the overall sum of all accounts before interest is added, the sum of all interest and total balance for each customer. See Figure 95.The array will be declared in main() and passed to two functions.The first function will be used to get user deposits, the second to do the calculations and output to screen.

Step 1 Before main() create a function prototype,void getDeposits(double Balance[][colSize],int ); This statement indicates there is a function that will be passed a 2 dimensional array with 3 columns. The number of rows and columns is determined within main(). Create a second prototype void passBalances(double Balance[][colSize],int );

This is used to do calculate balances and output to screen.Declare two constants for the rows and columns before the function prototypes.

const int rowSize =2;const int colSize =3;

the const qualifier can be used to declare a constant variable rowSize to 2. Note: constant variables must be initialised and cannot be changed. These are declared outside main() and can be seen by all functions.

Within main() declare the array and initialise the elements to zero. double Balance [rowSize] [colSize] = {0};

Create the function getDeposits() after main(). 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 132 November 2013

Page 142: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Create a second function void passBalances (double Balance[][colSize],int rS) after main()Calculations to establish the interest and balance for each customer should be done in the inner loop (column) of the array search. The following statements will establish the deposit, interest and total for each depositdeposited += 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 (rows) of the array searchOAdeposited += 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 2 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 133 OUCS

Page 143: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

10.5. Overloading functionsWhen 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 32Function Overloading Examine a program to see how functions can be overloaded

Task 1In eclipse, open the project OverloadingFunctions. Examine the program structure. There is one source file OverLoadingFunctions.cpp.

Step 1 Run the program. The output should be the same as shown in Figure 96.

Figure 96

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

void FtoCent(double temp);

Both prototypes return void and both have the same name. The parameters that are being passed are different, int and double .

Physics/ITLP 134 November 2013

Page 144: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 Examine the statementinValue = toupper(inValue); toupper is a member function in header file <cctype> that changes the input char to upper case. Using toupper means it is unnecessary to test for upper and lower case values input.

In the selection (if, else if, else) either an integer or double is read in, then the appropriate FtoCent 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 void FtoCent(double ITemp) used to convert a double value read into centigrade. The statement cout <<fixed<<setprecision(2); This statement sets the stream manipulators, fixed and setprecision. Another stream manipulator used in this function is setw. The header file <iomanip> 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 cout <<setw(5). This command does not produce any output but manipulates the stream to change the

November 2013 135 OUCS

Page 145: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

output format of the next value. Note: setw must be specified for every item output.The statement cout << fixed << setprecision(2) << setw(5) << ITemp; sets the precision of the following floating point number to 2 decimal places and the field width to 5. As fixed and setprecision only have to be used once, the above statement could be written as two statements cout << fixed << setprecision(2); cout << setw(5) << ITemp; avoiding repetition of fixed and setprecision with further statements. See Appendix 24.8 for more detail.

Task 2Modify the program in the previous task so the program can be used to convert temperatures from Centigrade to Fahrenheit as well as from Fahrenheit to Centigrade.

Overload the new function so the user can enter an integer or double to the program.

Step 1 Modify the program OverLoadingFunctionsThe formula for converting from Centigrade to Fahrenheit is f = ((9 * c)/5) + 32.0; f is the temperature in Fahrenheit and c is a temperature in Centigrade.

Task 3OPTIONAL Add a class header file to the project. Call it OverLoadingFunctions .h. Modify the program so the calculations are done within a class header file.

Physics/ITLP 136 November 2013

Page 146: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

10.6. Function TemplatesIn 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 (function template specialisations) 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 template followed by a list of template parameters enclosed in angle brackets template < typename T >. The keyword typename indicates that the value T will be a type and not a value. It can be a primitive type (int) or a class type (string). NOTE: Earlier versions of C++ used the keyword class for this purpose and the template prefix would be written as template <class T>. You can use either but the keyword typename is more descriptive.

November 2013 137 OUCS

Page 147: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 33Function Templates Examine a program to see how function templates can be used

instead of function overloading

Task 1In eclipse, open the project FunctionTemplate . Examine the program structure. There are two associated files: FunctionTemplate-Maximum.h FunctionTemplate-Maximum.cpp.

Step 1 Run the program, adding data as requested. The output should be the same as shown in Figure 97

Figure 97

Physics/ITLP 138 November 2013

Page 148: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Examine the header file FunctionTemplate-Maximum.h

template < typename T >

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

All function templates begin with the keyword template . The type template 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 template parameter T precedes the three arguments being passed, the return type and the variable maximumValue 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.

FunctionTemplate-Maximum.cpp 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 2 Create a new project, call it FunctionTemplateArrays.

Step 1 Create two files in the project. A class definition and the client code.In the header file create the class ShowArray In the class create a function template as shown in Figure 98 (or copy from FunctionTemplate-Arrays.txt)

November 2013 139 OUCS

Page 149: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 98

Step 2 In main() create three arrays. One with 45 randomly generated doubles, one with 45 integers and one with 10 strings.Create an object of class ShowArray with the statement ShowArray myShowArray; 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

Physics/ITLP 140 November 2013

Page 150: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

11 Pointers

In C++ programming data (variables) can be referenced by pointing to the address of a memory location.A pointer variable contains the address (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; age is a pointer, height 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 null pointer.Note:When the * is used in a variable declaration it indicates the variable being declared is a pointer and not a value .But do beware, when the * appears before a pointer variable elsewhere in the program it acts as an operator, called the dereference operator. 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 pointersPointers can be initialised in two ways. int x = 16, y = 69; /*variable declaration and initialisation*/

November 2013 141 OUCS

Page 151: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

1: int *x_ptr = &x; /*pointer declaration and initialisation. xptr points to the address of x*/2: int *y_ptr; /*pointer declaration. yptr is a pointer .*/ y_ptr = &y; /*Pointer initialisation. yptr points to the

address of y. */

Once declared, a pointer variable can be assigned the address of another variable using the & “address of operator”. 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 34Using pointers In eclipse, open the project Pointers Examine the structure of the program

Task 1In eclipse, open the project Pointers . There is one associated file, PointersMain.cpp.

Step 1 Compile the program, sorting any compilation errors.Run the program. The output should be the same as Figure 100.

Figure 100

Physics/ITLP 142 November 2013

Page 152: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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_ptr pointer declaration and initialisation.

int *y_ptr; Declaring another pointer y_ptr.

y_ptr = &y; Initialising y_ptr .

y_ptr = x_ptr; Assigning x_ptr address to y_ptr . Both pointers are pointing to variable X (16).

y_ptr = &y; Assigning the address of y back to pointer y_ptr .

*y_ptr = 170; Assign 170 to the variable at memory location stored in y_ptr . y_ptr points to variable y so 170 has been assigned to y.

11.2. Pointer Arithmetic and ArraysWe 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

November 2013 143 OUCS

Page 153: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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. It is not important to know how many bytes make up each element. Moving the pointer through the array with the assignment operator x_ptr += 2 will move two elements further through the memory allocated for the array, or 16 bytes for an array of doubles.

Exercise 35Pointers and Arrays In eclipse, open the project PointerArithmetic Examine the structure of the program

Task 1In eclipse, open the project PointerArithmetic . There is one associated file, PointerArithmeticMain.cpp.

Step 1 Compile the program, sorting any compilation errors.Run the program. The output should be the same as Figure 101.

Figure 101

Physics/ITLP 144 November 2013

Page 154: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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. int *x_ptr = intArray; 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; }

The statement x_ptr++; (Note: there is no dereference operator therefore x_ptr is pointing to a memory address) moves the pointer one address further along the array

In *x_ptr the * is used outside a variable declaration so it is acting as the dereference operator referencing the value at a memory location.

x_ptr--; (there is no preseeding dereference operator therefore the pointer is pointing to a memory address) moves the pointer one address back along the array. As this statement is in a for loop that repeats four times the pointer has been moved back to the beginning of the array.

The statement x_ptr +=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.

November 2013 145 OUCS

Page 155: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 2Create a new project, callit ReverseArray

In main() 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 main() .

Task 3 Create a new project, call it Array_Algorithm .Use STL global functions to manipulate an array.

Step 1 From the directory where you unpackedthe source materials, open the file called Array_Algorithm.txtReplace the default source file in the project with Array_Algorithm.txtAdd the necessary code so the output is the same as that shown in Figure 102.

Figure 102

Physics/ITLP 146 November 2013

Page 156: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

The array can be reversed using the algorithm reverse() and pointers to the beginning and end of array. A in place of iterator vec.begin() and A + 6 in place of vec.end().

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 reverse 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 vec.begin() and vec.end().Sort the array using the sort algorithm sort() and pointers 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 ptr is past end of the array: if(ptr = = A + elements) and if it is tell the user.

If the pointer ptr is not past end of array, the number is there. Output the value using pointer notation *ptr.

See section 24.13 for more information on vectors and global functions.

November 2013 147 OUCS

Page 157: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 4OPTIONAL 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 the program. See Figure 103.

Figure 103

Physics/ITLP 148 November 2013

Page 158: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

12 Classes and Interfaces12.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 36Creating an Interface Open an existing project Modify a header file Create an interface

Task 1In eclipse, open the project Header . There should be one associated source file: OxStudents.h . Modify the header file to create class definitions.Create an additional file detailing the member function definitions that represent the implementation of the class.

Step 1 In eclipse, open the project Header. If you do not have this project, go back to Exercise 13 and complete the task.Add a new Source file to the project, File | New | Source File Save and name the file OxStudents.cpp.

Step 2 Copy the class definition code from OxStudents.h file and paste it into the OxStudents.cpp file.Change the code in OxStudents.h so there is no implementation, see Figure 104

November 2013 149 OUCS

Page 159: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 104

Step 3 Add the directive #include "OxStudents.h" at the top of OxStudents.cpp Compile the program You should get a compilation error indicating a redefinition of class OxStudents. The class has already been defined in the .h file and a class cannot be defined twice.

Step 4 Remove the class definition by removing the line class OxStudents and the closing curly brace and semi-colon at the end of the fileRemove public:Change the function headers to match Figure 105 .

Figure 105

Notice that displayName is now preceded by the class name, OxStudents and :: the binary scope resolution operator . The member function is now related to the separate OxStudents class definition that contains the class data members and member function definitions.Compile and run the program

Physics/ITLP 150 November 2013

Page 160: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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

November 2013 151 OUCS

Page 161: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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

BirdsCompositionFriendClassFriends FunctionFuncRefValinlineHumPlacMammal(StudDefinitions)Inheritance DynamicInheritanceStaffJava.txtMult Base Class - StudentTeacherMultiple InheritanceOperator Overloading +Overload STREAM INSERTIONOverRideBaseClassmethsPolygonPurVirtualFunctionsRefSalaryRefSalary2strcatStrncatStudent ATM Abstract Balance Inquiry

Physics/ITLP 152 November 2013

Page 162: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

14 Inline functions, values and references14.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. inline int squareByValue( int ); 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 can ignore the call and for most functions with more than one statement typically will.

14.2. Functions, call by reference and call by valueIn 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 PointersCan be declared without initialisation

No Yes

Can be reassigned No YesCan contain a null value

No Yes

Easy to use Yes NoMost efficient Yes No

November 2013 153 OUCS

Page 163: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 37Examine 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 1In eclipse, open the project FuncRefValInline . Examine the structure of the project to identify different inline function calls, and the use of pointers and reference arguments with function calls.

Step 1 Open the PassByRefFunc project.

Step 2 Run the program. The output should be as shown in Figure 106.

Figure 106

Step 3 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 154 November 2013

Page 164: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 4 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; zRef is a reference to z. References must be initialised when declared.

Figure 108

November 2013 155 OUCS

Page 165: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 5 Examine the statement shown in Figure 109. :: is the unary scope resolution operator 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 6 Examine the rest of the program and then add zRef = &w; as shown in Figure 110. Compile the program.Explain what is happening and why the program will not compile.

Figure 110

Physics/ITLP 156 November 2013

Page 166: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

14.3. Reference parameters and classesWhen 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 staff object and double . Figure 112 shows the function call with an instance of Staff called John being passed with a double 10 .Figure 113 shows the function body. It receives the two parameters. The staff object emp is set to the same value as John and amount is set to 10. emp is then modified but the modification has no effect on John as emp is a separate object. When the function exits emp is forgotten and John doesn’t get a raise, most unsatisfactory. In the function raiseSalary(), emp is a value parameter because it is a variable initialised with a value supplied by the caller. We want emp to refer to the instance object John. We also need the salary of John to be updated with changes calculated within the function. To achieve this we make emp a reference parameter.

November 2013 157 OUCS

Page 167: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

emp is not a new variable but is a reference to John. Any changes to emp (via member function calls) actually change the variable to which it refers, in this case John.Reference parameters syntax is:

Staff & emp - staff object reference called empint & number - int reference called number

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 38Examine and modify class reference parameters Run the program and establish how the program works.

Task 1In eclipse, open the project RefSalary . Examine the structure of project and establish how the program works.Modify the program to use reference parameters so emp is a reference to an existing instance object John.

Step 1 Open the Staff project.

Step 2 Run the program. The output should be as shown in Figure 114.

Figure 114

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

Physics/ITLP 158 November 2013

Page 168: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 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 4 The answer is in section 14.2.

14.4. Constant objects and const member functions

The const keyword allows us to specify whether or not a variable is modifiable. We can use const to prevent modifications to variables, pointers and references. We can also create const 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 const 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 pointer to a const or a const pointer .const double *x = &a; //pointer to const double

this statement declares x as a pointer object to a const double. Here the value pointed at cannot change but the pointer can.

November 2013 159 OUCS

Page 169: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

double *const x = &a; //const pointer

this statement declares x as a object of type const pointer to a double. Here the value pointed at can change but the pointer cannot.Staff *const emp;

this statement declares emp as a object of type const pointer to an object of type Staff. Here the instance object pointed at can change but the pointer cannot.const Staff *const emp;

this statement declares emp as a object of type const pointer to a const object of type Staff. 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. References are constant by default .

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

declares a reference to a constant Staff instance object.

const Staff &const emp = Sarah;

declares a constant reference to a constant object and will cause a compilation error. References are constant and cannot be changed .

14.4.3 Constant member functions

const Shape rectangle(23,87.6);

declares a const object rectangle and initialises the width to 23 and height to 87.6. Any attempt to modify the object will cause a compilation error.

Physics/ITLP 160 November 2013

Page 170: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

double Shape::getArea() const{ return area;}The function above declares getArea as a constant member function. The function cannot modify the object (Shape object) in any way. It is effectively a "read-only" function. All member functions that do not modify the object should be declared const , whether the object is a const object or not.Note that we must add the const 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 39Modify constant pointers and references Run the program and sort compilation errors.

Task 1In eclipse, open the project RefSalary2Examine the structure of the project and establish how the program works. This is very similar to the program you used in Exercise 38.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 any const data.

Step 1 Look at all the files in the project and modify the program so that const references, pointers, objects and member functions are addressed correctly.

Step 2 When the program is compiled the output should be as shown in Figure 116 .

Figure 116

November 2013 161 OUCS

Page 171: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

15 More on Classes15.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.

Physics/ITLP 162 November 2013

Page 172: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Mammals.Mammals are vertebrate animals that are endothermic (warm blooded), have hair on their bodies, and produce milk to feed their babies.Placental MammalsThe 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.MonotremesMonotremes 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.MarsupialsMarsupials 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 class used previously.class Cat: public base_class_name is the essential syntax for inheritance. The syntax indicates that the class (Cat) will contain all public and protected (see section 15.3) data members of the base class (Placental Mammals). 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 163 OUCS

Page 173: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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. public: A data member or member function declared in a

public 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 encapsulation .

private : A data member or member function declared in a private section of a class can only be accessed by member functions and friends (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.

protected : A data member or member function declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes. See section 15.7 for more information on friends .

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 protected data is that derived classes can modify the base class data members directly (BaseClass::DataMember). 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

Physics/ITLP 164 November 2013

Page 174: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

implementation. To achieve this we should make data members private and provide public member functions to manipulate this data.

November 2013 165 OUCS

Page 175: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 40Base and Derived classes Examine the structure of base and derived classes

Task 1In eclipse, open the project InheritanceStaff.Examine the program to see how a derived class and base class are related.This program is used to collect data on staff in a business. All staff are part of a base class and have common attributes. The derived class is a manager 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

Step 1 In eclipse, open the project Staff

Step 2 Compile and run the program. The output should be as shown in Figure 119.Note how the first five prompts ask for data that is common to all members of staff (Name , DOB, DOJ, House Number and Post Code). The last two prompts ask for data that relates specifically to management staff. The manager’s title and number of staff they are responsible for.

Figure 119

Physics/ITLP 166 November 2013

Page 176: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

use existing class data and behaviours.

Step 3 In the Project/Class Browser, see Figure 120, you will see the main program file managerMain.cpp together with two .h (manager.h and staff.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 manager.cpp and staff.cpp that contain the detail of how the member functions work.

November 2013 167 OUCS

Page 177: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 4 Open manager.h . Examine the class definition class Manager : public Staff . The : colon character denotes inheritance. The keyword public is required. However, if we omit public the class definition will still compile. Manager will still inherit from Staff but will inherit privately. This means that only the member functions of Manager get to call the member functions of Staff . Whenever you invoke a Staff method on a Manager 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 manager.h has public member functions and protected 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, position and numStaff .The separate source code file manager.cpp contains the detail of the member function implementation.Note the use of the pre-processor directive #include "staff.h" at the top of the file. This is needed as the class manager inherits from staff. Without it the manager class does not know about the staff class members

Step 5 Open the file manager.cpp . The separate source code file manager.cpp contains the detail of the member function implementation and how the functions work.Note the use of const after the member functions. Constant member functions that never change a class member value should be declared as const . See Appendix 24.18 for more detail.

Physics/ITLP 168 November 2013

Page 178: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 6 Open the file staff.h. The interface staff.h has public member functions and private data members. Private data members can be accessed via member functions of it’s own class or member functions of the derived class manager using base class member functions. Note the set member functions that are used by the derived class to set the data members in the base class. There are also five const member functions to return data from the base class object.

Step 7 Open the file staff.cpp . The separate source code file staff.cpp contains the detail of the member function implementation for the base class and details how the functions workNote the use of const after the member functions. Again, constant member functions that never change a class member value should be declared as const .

Step 8 Open the file managerMain.cpp . This is the main file in which we create an instance of the derived class manager called man1 . 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. Man1.getName(), Man1.getnumStaff().Note that these member functions are functions in the base class staff, not the derived class.

November 2013 169 OUCS

Page 179: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

15.4. Member initialiser listIn 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 references and member objects must be initialised using the initialiser list .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.: position(pos), numStaff(ns), initialises the two derived class data members.Staff(name, DOB, DOJ, hNum, pCode) passes five arguments to the base class constructor.

Exercise 41Using an initialiser list Modify a program to use an initialiser list

Task 1In eclipse, open the project Staff you used in Exercise 40.

Step 1 Open manager.cpp and change the class constructor to match the constructor shown in Figure 121.Two arguments, pos and ns are being used in the derived class with the other five being passed to the base class constructor Staff(name, DOB, DOJ, hNum, pCode) .

Figure 121

Physics/ITLP 170 November 2013

Page 180: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Change the class header file manager.h to match the constructor implementation. Seven arguments are being passed to the derived class.

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

Step 4 Modify the statement Manager Man1(manTitle, numStaff); in managerMain() used to create and initialise the instance of Manager class. When creating the instance of Man1 you will have to pass all seven arguments.

Step 5 Remove the five statements from managerMain() 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.

November 2013 171 OUCS

Page 181: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

15.5. Preprocessor wrappper #indefAs 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 #ifndef and ends with #endif . The class definition for class Staff shown below is enclosed in a preprocessor wrapper #indef STAFF_H . indef means "if not defined". It prevents the code between #ifndef and #endif 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 staff.h has not been included previously in a file then the name STAFF_H is defined by the #define directive and the header file statements are included. If the header file has already been included it is not included again.

Figure 122

Physics/ITLP 172 November 2013

Page 182: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 42Add a preprocessor wrapper Add a preprocessor wrapper to the staff.h header file

Task 1Add a preprocessor directive to the staff.h file in the project used in Exercise 41.

Step 1 In eclipse, open the project Staff file in the InheritanceStaff folder.Add a preprocessor wrapper to the staff.h file.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 173 OUCS

Page 183: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 43Adding an additional class Add an additional derived class

Task 1We need to add another category of staff. Continue to use the program you worked on in Exercise 42.The new category is Administrative staff . Admin staff share all the base class data members attributes and can therefore be treated as a derived class of class staff.Modify the Staff 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.

Step 1 Add two new files. You need to add a class interface and a separate source code file (.cpp) that details the function implementation.The administrator details you will need are the building and office they work in.Remember to use a member initialisation list.

Physics/ITLP 174 November 2013

Page 184: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 123

November 2013 175 OUCS

Page 185: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

15.6. Overriding base class methodsA 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 const is used that must match as well.

Be aware that overriding base class methods can hide overloaded 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 moves() methods in the base class are hidden even though they have different arguments.

Note that base class methods can be called, MyCat.Mammal::moves(), by explicitly stating its class name, then the member function name separated by ::, the scope operator. It can be useful to call base class methods in this way that have been overridden by derived class methods.

Exercise 44Overriding Base Class Methods Examine the program to understand how to override base class

methods

Task 1In eclipse, open the project OverRideBaseClassMeths .In eclipse, open the project OverRideBaseClassMeths 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.

Step 1 Open OverRideBaseCM project, compile and run the program. The output should be as shown in Figure 124.

Physics/ITLP 176 November 2013

Page 186: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 124

Step 2 The program has a base class Mammal and a derived class Cat. The base class has overloaded functions moves() and moves(4) . The derived class also has function moves() . When an instance of Cat is created and the function moves() called this overrides both of the overloaded moves() functions in the base class.There appears to be no way that a Cat object can get access to the overloaded base class function moves(int) .

Step 3 In main.cpp change the statement MyCat.moves(); to MyCat.moves(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 moves(int) is hidden to any object of the derived class Cat.

November 2013 177 OUCS

Page 187: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 4 Examine the statement MyCat.Mammal::moves(4); Here we are calling the base class function moves(4) by explicitly stating the instance, base class name then member function separated by the :: scope operator .We commonly call base class methods in this way when they have been overridden by derived class methods.

Exercise 45Human Inheritance Create a new program that uses the class hierarchy shown in

Figure 117

Task 1Create a new project, call it HumPlacMammal .You will need to create three .cpp class files and then complete the detail member function implementation.You will need one Human , one Placental Mammal and a Mammal class. The class definitions have been created for you.

Step 1 Create a new project, call it HumPlacMammal.

Step 2 From the directory where you unpacked the source materials, open the file called HumPlacMammal(StudDefinitions). There are four files you will need. Add all four files to the project you have just created.

Physics/ITLP 178 November 2013

Page 188: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Using the skeleton framework in main() add instance and member functions calls for each of the three classes. Many member functions are overridden and you may have to call base class member functions directly.

Step 3 There are three .h header files showing the interfaces for the three classes shown in the hierarchy in Figure 117.Classes we are using are Human , Placental Mamma l and Mammal. The Human class is derived from Placental Mammal and this derived from Mammal.There is a framework for the main 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.

Figure 125

Step 4 Examine Figure 125. This shows how the program should look when it is run.An object of the Human 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. "walk erect on two feet" has been returned from member functions of one of the classes.

November 2013 179 OUCS

Page 189: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

Step 6 Using the main function file create an instance of the Human 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 180 November 2013

Page 190: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

15.7. Friends and FunctionsA friend can be either another class or function. Being a friend allows access to the data members and functions of a class from classes that are not derived classes. Normally, private and protected 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 'friends ' of the class. To declare an external function as friend 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 46Examine a friend function Examine the program to understand how a friend function can

access private data members of a class.

Task 1In eclipse, open the project FriendsFunction.Examine how a function can be used to access private and protected data members of a class.

Step 1 Open FriendsFunction project, compile and run the program. The output should be as shown in Figure 126.

Figure 126

November 2013 181 OUCS

Page 191: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Open the file main.cpp .Before main() 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 Rectangle rect(2,3); Here we are creating an instance of Rectangle class and initialising the data members width (2) and height (3).Beneath this a second Rectangle object is created Rectangle rectb; using the default constructor.The next statement of interest is rectb = duplicate (rect); Here we are calling the function duplicate and passing the object rect . This object has data members width (2) and height (3).

Step 4 Examine the Rectangle function Rectangle duplicate (Rectangle inrect)

{

Rectangle rect;

rect.width = inrect.width*2;

rect.height = inrect.height*2;

return (rect);

}

Inside the function a new Rectangle object is created, Rectangle rect; The data members of the object inrect are accessed, doubled, then assigned to the new object inrect. This is unusual as private and protected members of a class cannot normally be accessed from outside the same class in which they are declared.

Physics/ITLP 182 November 2013

Page 192: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 5 Open rectangle.h . Note that in the public section of the class definition the function duplicate has been declared as friend of the Rectangle class, friend Rectangle duplicate (Rectangle);Declaring a prototype of the external function within the Rectangle class, then preceding it with the keyword friend, means the function can access the private and public members of the class.

November 2013 183 OUCS

Page 193: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 47Add a friend function Add an additional class then use a friend function to access the

private data members.

Task 1Modify the program in the Friends Function project by adding a new class Triangle . Add a definition and source file. The data members are base and height .Add a constructor, destructor and member functions to set the data members and get the area.Add another friend function and prototype to main(). Call the function triangle .The area of a triangle can be calculated as half the base multiplied by the height. Add an additional function prototype to the triangle header file.Output the area of the new triangle object using the friend function to access the private data members of the class. Add an additional function prototype to the triangle header file.

Physics/ITLP 184 November 2013

Page 194: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

15.8. Friends and ClassesIn section 15.7 we have seen how to define a friend function. It is also possible to define a class as friend of another class . The second class (the friend class) is granted access to the protected and private members of the first class.

Exercise 48Using friend classes Examine the program to understand how a friend class can

access private data members of another class.

Task 1In eclipse, open the project FriendClass .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.

Step 1 Open main.cpp and examine the statements shown in Figure 127.

Figure 127

Here we are creating two instance objects, one Rectangle and one Square .Instance sqr uses the member function setSide(4) to set the dimension of the square.Instance rect calls the convert member function and passes the object sqr.

November 2013 185 OUCS

Page 195: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Open square.h . Examine the statement:friend class Rectangle;

This statement declares class Rectangle as a friend of Square . Rectangle can now access private and protected data members of instances of the Square class.Note: Friendship is one way. Rectangle is a friend of Square 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. Note: Frienships are not transitive. You cannot have a class as a friend of another friend class unless explicitly specified.Also note in "rectangle.h" that we use the pre-processor directive, #include "square.h" . This header file is included as we make reference to the class Square in the function 'convert '. Without the reference there is no way the compiler can know about the class 'Square' .

Physics/ITLP 186 November 2013

Page 196: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 Open rectangle.cpp and examine the function shown in Figure 128.

Figure 128

Function convert is passed a parameter of type Square (a) . In the statement width = a.side *2; a is the object and side is the data member of the class Square .So the private data members (side) in class Square have been accessed by public member functions of the Rectangle class. These have been assigned to the private data members of the Rectangle class, width and height .When the Rectangle member function rect.area() is called, the width and height of the Square object are used to calculate the area of the rectangle.

Step 4 Open rectangle.h . Notice at the top of the file the statement #include "square.h". This is included as we make reference to the Square class in the function convert(). Comment out the #include directive and see what happens when you re-compile.

November 2013 187 OUCS

Page 197: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 49Adding a friend class Modify the program adding a third class. Make this class a

friend of Rectangle class.

Task 1Expand the program used in Exercise 48. Create a new class Triangle .Add a function definition and source code file.The class will have data members width and height and a member function getArea() returning the area of a triangle.The area of the triangle can be calculated as ½ the width *height. The width and height are the private data members of the Rectangle class. Do these calculations in a function in Triangle that can be called from main() .Class Triangle will have to be declared as a friend of Rectangle .The triangle.h file will need to make a pre-processor reference to Rectangle as Rectangle objects are used in the class definition.

Step 1 Create two new files, triangle.h and triangle.cpp.

Physics/ITLP 188 November 2013

Page 198: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

15.9. CompositionWe have already seen that classes can be derived from other classes that provide attributes and behaviours the new classes can use (inheritance). When we include class objects as members of other classes we call it composition 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 public 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 references 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 50Composition, using objects as members of other classes

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

Task 1In eclipse, open the project Composition.Examine the code to see how Date class objects are used as data members of the Employee class.

Step 1 Compile and run the program. The program should look the same as Figure 129.

Figure 129

November 2013 189 OUCS

Page 199: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Open main.cpp and examine the statements shown in Figure 130.

Figure 130

The first two statements create two Date objects birth and hire . 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 Employee called staff and passes the employee first and last names and the two Date class objects to the class constructor.The seventh statement calls the print method using the staff object.

Step 3 Open Employee.h class definition. This is shown in Figure 131.The first statement is the class constructor. Two strings are being passed to the constructor representing the first and last names.Const Date & is passing a reference to the Date object for the DOB. The Date object is const and cannot be changed and represents the birth date.Const Date & is repeated (for the date hired) and the reference is passed to the data member for hireDate .

Physics/ITLP 190 November 2013

Page 200: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 Date .Note the use of #include "Date.h" in the Employee class definition. The Employee class is using objects of the class Date so must include the Date class definition. Doing this means the compiler knows about the Date class when the objects are passed via the constructor in Employee.cpp to the Date constructor.

November 2013 191 OUCS

Page 201: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 5 Open Employee.cpp. Examine Figure 132.This shows the class constructor using a member initialiser list to pass initialiser reference values to the Date member objects birthDate and hireDate 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.

Note: All data members can be initialised using a member initialisation list. However, const data members, data reference members and member objects must be initialised using a member initialisation list as we are here.

Figure 132

Physics/ITLP 192 November 2013

Page 202: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 6 Examine the code shown in Figure 133, the hireDate.print(); statement. The instance object hireDate is a reference to the instance (hire) passed from main to Employee. The reference is used in the member initialiser list (dateOfHire) to initialise the member object hireDate , hireDate(dateOfHire).hireDate.print(); calls the Date member function print() of the instance hire of the Date class. The print() function of the Date class object outputs the date the employee was hired.Ina similar way birthDate.print(); calls the Date member function print() of the instance birth of the Date class.

Figure 133

November 2013 193 OUCS

Page 203: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 51Composition, dates as object members of student class

Create a program to track student enrolment

Task 1Create 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;Create instances of the class Student 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 134

Figure 135

Physics/ITLP 194 November 2013

Page 204: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 52Composition, Starting the OUCS ATM Create a user interface for the new ATM, soon be introduced at

OUCS.

November 2013 195 OUCS

Page 205: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

Figure 136

Figure 137

Figure 138

Physics/ITLP 196 November 2013

Page 206: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

16 Operator OverloadingOne of the nice features of C++ is that you can give special meanings to operators 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 operator overloading . 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

November 2013 197 OUCS

Page 207: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 53Overloading the addition operator + Exam the structure of a program to learn how to overload the +

operator

Task 1 In eclipse, open the project Operator Overloading plus.Examine how to overload the addition + operator.

Step 1 Open mainComplex.cpp . Run the program and see how it works.

Figure 139

Examine the code shown in Figure 147. Here we are creating four objects of the CVector class and initialising three of the first four objects.

Physics/ITLP 198 November 2013

Page 208: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

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 complex.cpp .

Figure 141

Examine the function named operator+ shown in Figure 141. operator+ indicates the + addition operator is being overloaded.

November 2013 199 OUCS

Page 209: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 4 Examine the function operator+.The function operator+ 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 CVector 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 ‘operator+ ’ . The object b is passed as an argument to the operator ‘+’ inside the function ‘operator+’ and the real and imaginary elements are accessed as param.x and param.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 CVector.

The statement this->x + param.x; uses the 'this ' 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 'this '. Static data members and static member functions exist independently of any objects of the class and so cannot have a 'this ' pointer.

Objects use the 'this ' pointer implicitly. So, in CVector CVector::operator+ (CVector param) with no static data

Physics/ITLP 200 November 2013

Page 210: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 2Modify the program to sum the three CVector instance object data members.Compile and run the program and explain what is happening.

16.2. Overload stream operators

Exercise 54Overloading stream insertion operators Exam the structure of a program to learn how to overload the

stream insertion and extraction operators

Task 1 In eclipse, open the project Overload Stream Insertion.Examine how to overload the stream operators.

Step 1 Open main.cpp . Run the program and see how it works. The output should be the same as Figure 142.

Figure 142

November 2013 201 OUCS

Page 211: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 143

Step 2 Examine the code shown in Figure 143. Two objects of the class PartNumber have been created, part and part2 .The statement cin >> part is passing the istream object cin and the instance object part to the overloaded function operator>> .The statement cout << part is passing the ostream object cout and the instance object part to the overloaded function operator<<.

The overloaded function operator<< returns an ostream object with the data members of the part object concatenated.

Figure 144

Physics/ITLP 202 November 2013

Page 212: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 Open the implementation file SpareParts.cpp and examine the code shown in Figure 144.The overloaded operator>> function returns a reference to an istream object and takes two parameters by reference: These are an istream object and a user-defined type. The user-defined type 'PartNumber ' is not passed as a const parameter because the input operation can modify it. The body of the overloaded operator>> 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 SpareParts.cppThe overloaded operator<< function returns a reference to an ostream object and takes two parameters by reference:These are an ostream object and a user-defined type. The user-defined type 'partNumber ' is passed as a const parameter because the output operation doesn't modify it. The body of the overloaded operator<< function inserts members of the user-defined object into the ostream object.

November 2013 203 OUCS

Page 213: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 146

Step 5 Open the definition file SpareParts.h and examine the code shown in Figure 146.The two overloaded input and output operator functions are declared as friends because they need to access non-public (private and protected) class data members (Manufacturer etc) directly as the class does not have any get member functions. The two overloaded functions are not part of the class PartNumber 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 204 November 2013

Page 214: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

17 Dynamic Memory AllocationUntil 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 new and delete . The operator new 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] . new 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 int) as the program runs.delete number; This statement deletes the memory allocation.

pointer = new type [elements];int * nums ; declaring a pointer to an integer (nums).nums = new int [5] ; Pointer nums 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 Cat object.

ptrCat = new Cat("Mr Business") ; Allocate the memory for the Cat object. Call

the default constructor and return a pointer to the object memory location.

delete ptrCat; This statement deletes the memory allocation.

November 2013 205 OUCS

Page 215: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Physics/ITLP 206 November 2013

Page 216: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

17.1. Dynamic Cats

Exercise 55Dynamic memory allocation and pointers Exam the structure of a program to learn how to dynamically

allocate memory and then delete it.

Task 1 In eclipse, open the project Inheritance DynamicExamine how to dynamically allocate memory for a Cat object. Learn how to use pointers and pointer notation to access member functions.Learn how to dynamically allocate and delete memory.

Step 1 Open InheritanceMain.cpp .

Figure 147

Examine the code shown in Figure 147. The first statement creates a pointer ptrCat that will point to a Cat object.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 ptrCat and the arrow notation to point to the member function setAge() . A parameter 5 is passed. This sets the data member age in the base class to 5.The second statement uses the pointer and arrow notation to set the data member weight in the base class.Note how similar pointer notation is used to access other member functions.

November 2013 207 OUCS

Page 217: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 3 Examine the statement delete ptrCat; This statement frees the memory dynamically allocated with new .

Exercise 56Dynamic arrays Create a dynamic array and add additional objects.

Task 1 Using the Inheritance Dynamic project from Exercise 55 add a dynamic array to add two additional Cat objects.

Step 1 Open InheritanceMain.cpp . Add the code to create a dynamic array of cats.Remember to take care when using pointers to loop 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.

Physics/ITLP 208 November 2013

Page 218: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

November 2013 209 OUCS

Page 219: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

18 Pointer-Based string processing18.1. Characters and Pointer-Based strings

In the previous sessions you have used the Standard Library string class and created string objects. Programs can also contain character constants that can represent any key on the keyboard, plus the machine’s character set. A character constant 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 string literals or string constants in the following way, “Janine Caulder”, “01865 282828”. 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”; Oxford 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 city_Ptr to point to the letter ‘O’ in string literal “Oxford”. 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 cin .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 cin is that a white space will terminate the reading process and not all the characters will be stored. C++ provides the getline() function in the <iostream> 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 (city), 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

Physics/ITLP 210 November 2013

Page 220: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

met or EOF indicator is entered (Ctrl+z for Windows, Ctrl+d for Linux). If the delimiter is met it is not stored.

November 2013 211 OUCS

Page 221: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

18.2. String manipulation FunctionsThe 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 57Copying, concatenating and tokenising strings Examine a program to see how pointer based string manipulation

functions can be used.

Task 1In eclipse, open the project strcatStrncat .Examine the use of string manipulation functions

Step 1 Open the project strcatStrncat and run the program. Add your name when prompted. The output should be as shown in Figure 150.

Figure 150

Physics/ITLP 212 November 2013

Page 222: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 getline() . getline() will read into the array 25-1 characters. The ending null character 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.

November 2013 213 OUCS

Page 223: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 4 Examine the statement shown in Figure 153.

Figure 153

This function is similar to replace() 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 strcpy() 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

Physics/ITLP 214 November 2013

Page 224: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 6 Examine the statement shown in Figure 155.

Figure 155

Ptr is a pointer to type char, declared at the start of the program.A pointer is assigned by strtok to Ptr and points to the first character in the array a . strtok 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. strtok saves (static var) a pointer to the next character following the token in array a and returns a pointer to the current token.

Step 7 Examine the code shown in Figure 156. The while loop is used to continuously call strtok. Subsequent calls to strtok have NULL as the first argument.The NULL argument indicates strtok should tokenise from the saved pointer location in array a . When there are no tokens remaining strtok returns NULL .NOTE: strtok 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

November 2013 215 OUCS

Page 225: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

Exercise 58Use string manipulation functions to modify a program

Modify the program in Exercise 50 to use standard <cstring> library functions to check the length of names input.

Task 1Copy your folder Composition from Exercise 50 and save it as CompCString .Modify the program to use pointer based strings.The changes to the class definition (.h) file are shown in Figure 157.

Step 1 const char *const , signifies a constant pointer to constant data.The class implementation file (.cpp) should use functions:strlen to get the length of the strings read and,strncpy to copy the characters read in to the two arrays, up to a maximum declared in the header file. See Figure 157 for the character array sizes.

Figure 157

Physics/ITLP 216 November 2013

Page 226: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 59Using 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 1From the directory where you unpackedthe source materials, open the file called Java.txt .The text file contains a paragraph of text that we need to analyse.

Step 1 Using the program in Exercise 57 as a guide initialise an array with the data in the Java.txt file.The program should allow the user to search for a user input word.We also need to establish the following:Number of characters in the complete paragraph.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

November 2013 217 OUCS

Page 227: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

19 PolymorphismIn 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 virtual functions and base class pointersPolymorphism 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 virtual function through a base class pointer or reference . 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 base class. Its functionality can be over-ridden in its derived classes and the whole function body replaced with a new set of implementation in the derived 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, fly() and walk().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 base class pointer , we need all three classes to have fly and walk functions. The secret to using polymorphism in C++ is to create a virtual member function in the base class. Its functionality can be over-ridden in its derived classes using functions with the same name as

Physics/ITLP 218 November 2013

Page 228: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

the virtual function. The whole function body is replaced with a new set of implementation in the derived class.

19.1. Polymorphism

Exercise 60How 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 In eclipse, open the project Birds.Examine how a pointer to a base class is type-compatible with a pointer to a derived class. Understand how virtual member functions used in a base class can have their functionality over-ridden in the derived classes. The whole function body in the base class can be replaced with a new set of implementation in the derived class.

Step 1 In eclipse, open the project Birds . Compile and run the program. The output should be the same as that shown in Figure 160.The output shows how by using a base class pointer and assigning a reference to a derived class object it is possible to access the member functions of the derived class. It also shows how by using virtual functions and polymorphism it is possible for a virtual base class member function to be over-ridden by any virtual function in the derived classes with the same name.As both derived classes have talk() functions and talk() is a virtual function in the base class then the derived class talk() functions will override the base class function.

Figure 160

November 2013 219 OUCS

Page 229: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 2 Open main.cpp . Examine the statements shown in Figure 161.

Figure 161

Duck myDuck; creates an object of type Duck called myDuck.The next statement creates a base class pointer Ptrb of type Bird . Assigned to the base class pointer is a reference to a Duck object, myDuck .It is now possible to use polymorphism to invoke a virtual function in a derived class through a base class pointer or reference . C++ dynamically selects the correct virtual function in the derived class using the reference object assigned to the base class pointer.The virtual 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.

Physics/ITLP 220 November 2013

Page 230: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 3 Open the base class definition bird.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 virtual. 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 walk().The last statement defines a virtual function talk(). Declaring the function as virtual 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 Duck and Pigeon .

November 2013 221 OUCS

Page 231: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 4 Open the base class implementation file bird.cpp . Examine the code shown in Figure 163. There is a class constructor, a destructor and two member functions.The base class functions are walk() and the virtual function talk(). The talk() function in this base class will be overridden by the talk() functions in the derived classes Pigeon and Duck 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 222 November 2013

Page 232: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 5 Open the Duck class definition file duck.h . Examine the code shown in Figure 164.

Figure 164

The first statement declares a function to override the base class function talk().Note: It is not strictly necessary to add virtual 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 walk(). However, the function walk() 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 Duck object, but walk() is not a virtual function therefore the base class function walk() will always be called. Only member functions that are virtual will be overridden by the derived class function. Function walk() is not a virtual function so the pointer will use the base class function walk().

Step 6 Open the Duck class implementation file duck.cpp. Examine the code shown in Figure 165The two functions are talk(), the virtual function that will override the base class function and walk(). Derived class walk() can not be called as the base class pointer (Ptrb) used to access the member functions cannot be used to access a non-virtual member function.

November 2013 223 OUCS

Page 233: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 165

Step 7 Examine pigeon.h function definition and pigeon.cpp the implementation file. These derived class member functions work in a similar way to the derived class Duck described in Exercise 60 Task 1.

Exercise 61Accessing 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 walk().There are two ways to do this. Firstly it is possible to make the walk() functions virtual . 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 Bird. This is a base class pointer and

Physics/ITLP 224 November 2013

Page 234: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

by using this base class pointer and virtual functions we can gain access to derived member functions that are also virtual. 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 Duck class?

November 2013 225 OUCS

Page 235: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 62Implement polymorphismModify a program to allow a base class pointer to access derived member functions.

Task 1 In eclipse, open the project Polygon .Modify the program.

Step 1 Run the program. The output should be as shown in Figure 166.

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 rect.area() and trgl.area().

Physics/ITLP 226 November 2013

Page 236: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Member functions (virtual) should be accessed with the following notation poly1->area() , poly2->area() where poly1 and poly2 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 protected data members width and height in class Polygon . Protected data members can be accessed by member functions of its own class and by member functions of derived classes.

November 2013 227 OUCS

Page 237: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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 PredicatesDeques and IteratorsIO Basic IN_OUTLists and IteratorsMultimap ContainerMultiset ContainerPureVirtualFunctionsVectors and Iterators

Physics/ITLP 228 November 2013

Page 238: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

21 Abstract ClassesAll 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 abstract classes.Abstract classes are usually used as base classes. Abstract classes can never be instantiated and require the derived classes to complete the class before instantiation.If there is an abstract class then there is a good chance there is also a concrete 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 abstract class Shape and then derive concrete classes with the specific detail necessary to instantiate an object. The concrete classes might be Circle , Square and Triangle . Figure 167 shows a primitive inheritance hierarchy for shapes.

Figure 167

In Figure 167 we can define Shape as an abstract class. It would be extremely difficult to define the data members and member functions for a shape 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 Circle , Rectangle and Triangle .To create an abstract function we need to make one of its virtual functions a pure virtual 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?

November 2013 229 OUCS

Page 239: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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.

21.1. Examining an Abstract Class

Exercise 63Abstract classes & dynamic binding Examine a program to establish how abstract classes work. Look at dynamic binding.

Task 1 In eclipse, open the project PureVirtualFunctions .Examine the program to establish how to create an abstract class.Understand how to create a pure virtual function and understand the difference between a virtual function and pure virtual function.You will also be introduced to static and dynamic binding .

Step 1 In eclipse, open the project PureVirtual . Compile and run the program. The output should be the same as that shown in Figure 168.This program allows us to create two members of staff. Salaried and Hourly paid. There is a base class Employee and two derived classes Salaried and Hourly.The output for each of the two instance objects appears twice to demonstrate the use of static and dynamic binding.

Physics/ITLP 230 November 2013

Page 240: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 168

Step 2 Open main.cpp . Examine the statements shown in Figure 169.

Figure 169

This is a function prototype receiving a constant pointer to a constant object, base class object 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 sEmployee of class Salaried and initialises the data members via the constructor.The second statement creates an instance hEmployee of class Hourly and initialises the data members via the constructor.

November 2013 231 OUCS

Page 241: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 170

Step 4 Examine the statements shown in Figure 171. The statement sEmployee.print() is using the dot member-selection operator “object.method()”. This means the compiler can identify (knows about) each object (sEmployee and hEmployee) at compile time and knows which print and earnings functions to call. This is static binding.

Figure 171

Step 5 Examine the statements shown in Figure 172.

Figure 172

In this statement we create a vector to hold pointers of type Employee class. The vector has an initial size of two elements.

Physics/ITLP 232 November 2013

Page 242: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 6 Examine the statements shown in Figure 173.

Figure 173

Here the vector is initialised with addresses of Salaried Employees and Hourly paid Employees. The addresses are stored in base class Employee 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 for loop lets us loop through the vector elements and pass the address of each object to the function virtualPointer .

Figure 174

Step 8 Examine the statements shown in Figure 175. Both statements are used to access virtual functions.The first statement calls the print() function using the base class (Employee) pointer and the arrow notation (->). This calls the derived class print() function.

November 2013 233 OUCS

Page 243: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

The derived class member function then calls the base class print() function to access base class data members Firstname , LastName and NI number . The second statement accesses the derived class function of the base class pure virtual function earnings() . Again the baseClassPtr is used to access the derived class function print() . Function virtualPointer does not have any information on the derived classes. It is just being passed pointer information about the base class Employee . 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 baseClassPtr (Employee) points at that time. This is dynamic binding .

Figure 175

Physics/ITLP 234 November 2013

Page 244: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 64Create a new Abstract class Create a new abstract class Shape with three derived classes.

Task 1 Create a new project, call it Shapes .

Step 1 Using the hierarchy shown in Figure 167 create an abstract class Shape with no implementation.Step 2 Create three derived classes, Parallelogram , Rectangle and Triangle . 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 235 OUCS

Page 245: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 65ATM, base class pointers and private utility functions

Create a new abstract class Shape with three derived classes.

Task 1 In eclipse, open the project Student ATM Abstract Balance Inquiry

Step 1 Open ATM.cpp . Examine the statement:Transaction * transactionPtr;

This statement creates a base class pointer (transactionPtr) to the Transaction class. Transaction is an abstract 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 BalanceInquiry , Deposit and Withdrawal. See Figure 176.Note the common behaviour for the derived classes is run() .

Figure 176

Physics/ITLP 236 November 2013

Page 246: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 2 Examine the statement: transactionPtr = createTransaction(selection);createTransaction() is a private utility function and can only be accessed from within the class.selection is the user input choice from the menu (1-4). createTransaction returns a pointer of type determined by the user input (1-4).

Figure 177

November 2013 237 OUCS

Page 247: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 3 Examine the createTransaction() function shown in Figure 177.The function receives an integer (user input) that corresponds to the action the user wants to take, Balance Inquiry , Withdrawal or Deposit. Case select option 3 (Deposit) is not functional just yet so there is a prompt to let the user know.If the user inputs a 1, a BalanceInquiry object is dynamically created and assigned to a base class pointer tempPtr .Similarly if the user inputs a 2, a Withdrawal object is dynamically created and assigned to the base class pointer tempPtr .The base class pointer is returned to the calling function and assigned to another base class pointer, see Figure 178.

Figure 178

Physics/ITLP 238 November 2013

Page 248: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 4 Examine the statement shown in Figure 179.

Figure 179

The transactionPtr 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 base class pointer is type compatible with all three pointer types, it now points to an object of type BalanceInquiry . The statement shown in Figure 179 therefore invokes the virtual function in BalanceInquiry to get the user balance.

Task 2 Create a new class Deposit 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 OUCS ATM .

November 2013 239 OUCS

Page 249: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

22 Completing the OUCS ATM

Exercise 66OUCS ATM class diagram Add additional classes to the ATM.

Task 1Using 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 240 November 2013

Page 250: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

November 2013 241 OUCS

Page 251: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 181 Class diagram of OUCS ATM

OUCS 242 February 2007

Page 252: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

23 The Standard Template LibraryThe 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 first-class containers . Other containers are called adapters and near containers . Pointer based arrays, string, bitsets and valarrays are near containers, we will not be looking at those in this session.

Containers in the STL fall into two categories, sequence containers see Table 8, and associative containers see Table 9.

sequence containersvectorlistsdeque

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 containerssetmultisetmapmultimap

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?

November 2008 243 OUCS

Page 253: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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.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 containersType obj Allows initialization through default constructor Type newobj(srcobj) Copies constructor, Type(object) = object

Type newobj(beg, end) Creates container and copies elements from beg to end

obj.size( ) Returns the number of elements in object obj.empty( ) Returns a bool stating whether container is empty

obj.max_size( ) Returns the maximum number of elements 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 containerobj.clear( ) Erases all elements from containerobj.insert(position,element) Inserts a copy of element.

Table 10

* A predicate is an expression that returns either true or false.

OUCS 244 November 2008

Page 254: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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. size(). size() member function will return the number of elements of any container type it is used with.

23.3. AlgorithmsThe STL provides many standard algorithms that can be used generically across a variety of containers.The header <algorithm> 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++ Algorithmsaccumulate sum up a range of elementsadjacent_difference compute the differences between adjacent

elements in a rangeadjacent_find finds two items adjacent to each otherbinary_search determine if an element exists in a certain

rangecopy copy some range of elements to a new locationcopy_backward copy a range of elements in backwards order count return the number of elements matching a

given valuecount_if return the number of elements for which a

predicate is trueequal determine if two sets of elements are the sameequal_range search for a range of elements that are all

equal to a certain elementfill assign a range of elements a certain valuefill_n assign a value to some number of elements

November 2008 245 OUCS

Page 255: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

C++ Algorithmsfind find a value in a given rangefind_end find the last sequence of elements in a certain

rangefind_first_of search for any one of a set of elementsfind_if find the first element for which a certain

predicate is truefor_each apply a function to a range of elementsgenerate saves the result of a function in a rangegenerate_n saves the result of N applications of a functionincludes returns true if one set is a subset of anotherinner_product compute the inner product of two ranges of

elementsinplace_merge merge two ordered ranges in-placeis_heap returns true if a given range is a heapis_sorted returns true if a range is sorted in ascending

orderiter_swap swaps the elements pointed to by two iteratorslexicographical_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 elementsmax returns the larger of two elementsmax_element returns the largest element in a rangemerge merge two sorted rangesmin returns the smaller of two elementsmin_element returns the smallest element in a rangemismatch finds the first position where two ranges differnext_permutation generates the next greater lexicographic

permutation of a range of elementsnth_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 rangepartial_sort_copy copy and partially sort a range of elementspartial_sum compute the partial sum of a range of elementspartition divide a range of elements into two groupspop_heap remove the largest element from a heapprev_permutation generates the next smaller lexicographic

OUCS 246 November 2008

Page 256: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

C++ Algorithmspermutation of a range of elements

push_heap add an element to a heaprandom_shuffle randomly re-order elements in some rangeremove remove elements equal to certain valueremove_copy copy a range of elements omitting those that

match a certian valueremove_copy_if create a copy of a range of elements, omitting

any for which a predicate is trueremove_if remove all elements for which a predicate is

truereplace replace every occurrence of some value in a

range with another valuereplace_copy copy a range, replacing certain elements with

new onesreplace_copy_if copy a range of elements, replacing those for

which a predicate is truereplace_if change the values of elements for which a

predicate is truereverse reverse elements in some rangereverse_copy create a copy of a range that is reversedrotate move the elements in some range to the left by

some amountrotate_copy copy and rotate a range of elementssearch search for a range of elementssearch_n search for N consecutive copies of an element

in some rangeset_difference computes the difference between two setsset_intersection computes the intersection of two setsset_symmetric_difference

computes the symmetric difference between two sets

set_union computes the union of two setssort sort a range into ascending ordersort_heap turns a heap into a sorted range of elementsstable_partition divide elements into two groups while

preserving their relative orderstable_sort sort a range of elements while preserving order

between equal elementsswap swap the values of two objectsswap_ranges swaps two ranges of elementstransform applies a function to a range of elements

November 2008 247 OUCS

Page 257: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

C++ Algorithms

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 iteratorsSTL iterators (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.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 begin() and end(). begin() returns an iterator pointing to the first element in the container and end() returns an iterator pointing to the first element past the end of the container.If we assume an iterator “itr” points to the first element of a container, ++ itr points to the second element and * itr refers to the element pointed at by itr. Note that the iterator resulting from end() can only be used in an equality or inequality comparison to determine whether the iterator “itr” has reached the end of the container. This is because the member function end() returns an iterator that refers to a position past the last element in a container and not the last element of the container.

Iterator Typesinput 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

OUCS 248 November 2008

Page 258: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Iterator Typessupport 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.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, random access 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.

November 2008 249 OUCS

Page 259: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 182

Table 13 show the iterator types supported by different containers.

Sequence containers (first class) Iterator categoryvector random accessdeque random accesslist bidirectionalAssociative containers (first class)set bidirectionalmultiset bidirectionalmap bidirectionalmultimap bidirectional

Table 13

Iterator operationAll iterators

++p preincrement an iteratorp++ postincrement an iteratorInput iterators

*p dereference an iteratorp = p1 assign one operator to anotherp == p1 compare iterators for equalityp != p1 compare iterators for inequalityOutput iterators

*p dereference an iterator

OUCS 250 November 2008

Page 260: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Iterator operationp = p1 assign one operator to anotherForward iterators forward iterators contain all the

functionality of both input iterators and output iterators

Bidirectional iterators

--p pre-decrement an iteratorp-- post-decrement an iteratorRandom access iteratorsp += i increment the iterator p by i positionsp -= i decrement the iterator p by i positionsp + i Expression value is an iterator positioned

at p and incremented by i positionsp - i Expression value is an iterator positioned

at p and decremented by i positionsp [i] Return a reference to the element offset

from p by i positionsp < 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 iterators and many algorithms act on sequences of elements defined by pairs of iterators . 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. In the example below the sort() algorithm is using two iterators pointing to the start and end of the vector called myVector ;sort (myVector.begin(),myVector.end();

November 2008 251 OUCS

Page 261: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Because sort() algorithm uses random-access iterators to the initial and final positions of the sequence to be sorted, sort () can be used with the vector and deque containers but not the list container. Lists only support bidirectional iterators. However, list containers have a member function sort() that can be used to sort list elements. Table 13 shows the different iterators supported by each container. Table 15 shows predefined iterator typedefs found in the class definitions of the STL containers.

Predefined typedefs for iterator types Direction of ++ Capabilityiterator forward read/writeconst_iterator forward readreverse_iterator backward read/writeconst_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, vector, list and deque .

The STL algorithms can also be decoupled from the STL container classes. What this means to us is that certain algorithms (reverse 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 list container class also has a member function called reverse .

If we had created a list in our program called addresses 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 reverse algorithm with the list container is because reverse uses bidirectional iterators supported by the list container.

OUCS 252 November 2008

Page 262: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Vector Member Functions List Member Functionsvector::assign vector::max_size list::assign list::pop_front

vector::atvector::operator = list::back

list::push_back

vector::backvector::operator [ ] list::begin

list::push_front

vector::begin vector::pop_back list::clear list::rbegin

vector::capacityvector::push_back list::empty list::remove

vector::clear vector::rbegin list::end list::remove_ifvector::empty vector::rend list::erase list::rendvector::end vector::reserve list::front list::resize

vector::erase vector::resizelist::get_allocator list::reverse

vector::front vector::size list::insert list::sizevector::get_allocator vector::swap list::max_size list::sortvector::insert list::merge list::splice

list::operator = list::swaplist::pop_back list::unique

Table 16

Deque Member Functions

deque::assigndeque::operator =

deque::atdeque::operator [ ]

deque::back deque::pop_backdeque::begin deque::pop_front

deque::cleardeque::push_back

deque::emptydeque::push_front

deque::end deque::rbegindeque::erase deque::renddeque::front deque::resizedeque::get_allocator deque::sizedeque::insert deque::swapdeque::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.

November 2008 253 OUCS

Page 263: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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 (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 <fstream> header file. This allows the use of ofstream 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 outFile is created.

or by calling member function open. ofstream outFile;outFile.open("Numbers.txt", ofstream::out );

ios::out and ofstream::out are modes the file will be opened in. In the above cases out denotes writing to file with any existing data in the file being deleted. Mode ios::app appends data to the file.

When data has been transferred to file the interface can be closed (or disassociated) by calling member function close, outFile.close(); Once closed, the same file stream object can be used to open another file.

To read from a file the ifstream 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 open .

ifstream inFile; inFile.open("Numbers.txt", ofstream::in );

After all data has been transferred the interface can be closed (or disassociated) by calling member close . Once closed, the same file stream object may be used to open another file.

The member function is_open can be used to determine whether the stream object is currently associated with a file.

OUCS 254 November 2008

Page 264: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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

Exercise 67Using files to add data to containers Open an existing program and examine the code Modify the program to append data to file

Task 1In eclipse, open the project FileIO in the IO Basic IN_OUT folder and examine the code to establish how to read and write files.

Exercise 68 Open FileIO project and examine the code. Only the parts that relate to writing to and reading from file are covered here.The <fstream> header file is included to allow the use of ofstream and ifstream classes to create instance objects to read and write to and from file.Exercise 69ofstream outFile("Numbers.txt", ios::out );The statement above creates an instance of ofstream called outFile . The ofstream constructor takes two arguments, the name of the file and how the file should be opened. In this example out indicates any data in the file will be overwritten. ios::app 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. Note that it is unnecessary to write ios::out so the line could have been written ofstream outClientFile( "clients.txt");

Exercise 70 if (outClientFile.fail()) fail() is a member function that the ofstream object outFile inherits. If for some reason the file cannot be opened for writing an error message is given and the function exit 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.

November 2008 255 OUCS

Page 265: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 71 while(count < intStore.size()) uses a while loop to loop through vector intStore. Member function size() gets the number of elements in the vector to control the while loop outputting each element to file followed by the return character endl .

Step 1 outFile << intStore.at(count)<<endl;outFile is the object that points to the file Numbers.txt. Each element in the intStore vector is passed to file together with the end of line character using stream insertion operators <<. outFile.close(); 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 ifstream called inFile . The ifstream constructor takes two arguments, the name of the file and how the file should be opened, in this case we are reading in . inFile.clear(); resets eof for input, though this is not really necessary here as inFile has just been created.inFile.seekg(0); positions pointer to beginning of file, again as we’ve just created inFile , it’s not strictly necessary.

Step 3 If(inFile.fail())fail() is a member function that the ifstream object inFile 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 exit called and the program terminates.

OUCS 256 November 2008

Page 266: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Step 4 while(!inFile.eof()) { inFile >> r; storeSort.push_back(r); }The while loop reads the integers input stream object inFile while not meeting the end of file character. Each integer is stored in variable r and then pushed onto the vector storeSort .inFile.close(); closes the file.

Step 5 The statement storeSort.erase(storeSort.end()-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 endl 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 sort(storeSort.begin(),storeSort.end()); sort is an algorithm that uses random access iterators. The sort() algorithm sorts the elements in the range [storeSort.begin(),storeSort.end()] into ascending order with the elements being compared using a default < (less than) operator.

November 2008 257 OUCS

Page 267: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Step 7 for (int i = 0; i < storeSort.size(); i++)outputLine(storeSort[i]);The for loop is used to iterate through the vector passing each element in turn to the function outputLine where it is output. A static counter in the function outputLine (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.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, myVector[10];

OUCS 258 November 2008

Page 268: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Vectors support random access iterators 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 72Vectors, iterators and algorithms Examine the code to recognise and understand iterators &

algorithms Modify the program

Task 1Open VecsAndIts in the Vectors and Iterators folder and examine the code to establish how to read and write files.

Exercise 73Open VecsAndIts and examine the code. Only the parts that relate to vectors, iterators and algorithms are covered.Have a look at the code shown in Figure 183. The code shows the function prototype for template function OutPutVectorElements . 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 constant so any iterators we use must also be constant.

Figure 183

Exercise 74 In the statements doubs.push_back(a+1.3); and ints.push_back(a+1); we use the vector member function push_back(). push_back 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.

November 2008 259 OUCS

Page 269: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 75 The statement OutPutVectorElements(ints); passes the vector ints to the template function.

Exercise 76 Examine the code shown in Figure 184. The statement is used to create a constant reverse iterator called conRevIt . Notice that const_reverse_iterator is a forward only iterator, see Table 14. This means, as the names suggest the iterator can only move forwards through the container. Importantly, forward iterators 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 rend() . The significance of this is explained in the next step.

Figure 185

OUCS 260 November 2008

Page 270: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 78 In Figure 186 the for loop condition is testing to see if the iterator conRevIT is not equal to iterator conTempIT . It would seem intuitive to write this conditional statement as conRevIT < conRevIT.rend()However, conRevIT is a forward iterator and does not support the < operator so we assigned the iterator rend() to conTempIT (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 constant iterator that can read a const element in a vector.

Figure 187

Exercise 80 In Figure 188 the for loop condition is testing to see if the iterator conIT is less than the iterator returned by inValue.end().Note that we can use the test condition operator < (less than), as conIT is a random-access iterator.

November 2008 261 OUCS

Page 271: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Figure 188

Task 1 Modify the program to read from file ints.txt all the values into a vector of integers. Show the vector before and after sorting.Read in the values from doubs.txt . Use the template function to show the vector before and after sorting. The output should be similar to Figure 189

Figure 189

OUCS 262 November 2008

Page 272: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 81Calculating the min, max and mean of vector elements

Import data into vector Establish the max, min and mean values

Task 1Create a new project.Read the data from the file doubs.txt into a vector.Establish the max, minimum and mean values in the vector.

Exercise 82The max and min values can be established using the STL algorithms, max_element and min_element . max_element returns an iterator pointing to the largest element in a range and min_element returns an iterator pointing to the smallest element in a range.The format for min_element is shown in Figure 190. You will also need to create a vector iterator to assign the returned iterator to. In this example it’s called myIterator , myIterator can be used with the dereference operator to output the minimum and maximum values, see Figure 191.Note, remember to include the header <algorithm> .

Figure 190

Figure 191

Exercise 83 Create a template function that can take any kind of vector and the code necessary to calculate the median 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.

November 2008 263 OUCS

Page 273: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 84

Figure 192

OUCS 264 November 2008

Page 274: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

23.8. Using the list class containerLists 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 any location in the container. A vector is efficient when inserting and deleting at the end and deques are efficient when inserting and deleting at the front and back of a container. Lists are implemented as double-linked lists that store each of the elements they contain in different and unrelated storage locations . The ordering is kept by the association to each element of a link to the element preceding it , and a link to the element following it .Some of the advantages of using list containers are: Efficient insertion and removal of elements anywhere 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), lists perform generally better with insertion , extraction and moving elements in any position within the container.The main drawback with using lists compared to these other sequence containers is that they lack direct access to the elements by their position 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.

November 2008 265 OUCS

Page 275: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 85Using 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 1Open ListsAndIts file in the Lists and Iterators folder and examine the code to establish how to use the list container.

Exercise 86Only the parts that relate to lists, iterators and algorithms are covered.The code shown in Figure 193 shows the instantiation of two iterators that will be used with list containers holding data type double.

Figure 193

Exercise 87 In Figure 194 the push_back member function is used to add values to the end of the list. List containers also have member functions push_front and pop_front allowing insertion and removal of elements from the front of the list.

Figure 194

OUCS 266 November 2008

Page 276: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 88 In Figure 195 a reference is assigned to iterator it1 of the first element in the list doub.begin() .insert() member function adds an element before the element pointed at by iterator it1 . In this example we are adding 69.69 at the beginning of the list. Note: after insert() iterator it1 is still pointing at the same value in the list that was identified as doub.begin() , i.e. now the second element.Note: this version of the insert() member function returns an iterator pointing to the newly added element. However, as shown here, it does not have to be used.

Figure 195

Exercise 89 In Figure 196 the sort() 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

November 2008 267 OUCS

Page 277: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 90 In Figure 197 the sort() member function is used sort the list doubs() .The merge member function is then used to merge doubs with list doub , the merge is to list doub . Note that this will empty the second list doubs .

Figure 197

Exercise 91 In Figure 198 we want to copy the contents of doub() list to the now empty list doubs() . To do this we use the copy() algorithm.The copy algorithm uses input iterator and output iterator that are supported by list containersNote: before using the copy algorithm the list doubs() has to be resized using list member function resize() to match the size and number of elements that will copied into it.

Figure 198

OUCS 268 November 2008

Page 278: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 92 In Figure 199 the unique 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 doub with the content of doubs . Obviously both lists must contain elements of the same type but list sizes may differ.After the call to the member function the elements in doub container are those which were in doubs , and the elements of doubs are those which were in doub . Note that an algorithm exists with the same name swap , which has the same behaviour.

Figure 200

November 2008 269 OUCS

Page 279: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 94 In Figure 201 iterator it1 is positioned at the start of the list using function begin() .STL class iterator advance() advances the iterator it1, twice to the third element of the doub list. Iterator it1 will be used with the splice() member shown in Figure 202.

Figure 201

Exercise 95 Figure 202 member function splice() is used to move elements from list to list. Elements are moved from myList into the list container doub at the specified position it1 . Note: iterator it1 has already been moved to the third element position. The element at location it2 in myList, “10” is moved from myList into list doub . myList has one element less and doub has one element added at position it1.

Figure 202

OUCS 270 November 2008

Page 280: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 96 Figure 203 shows how to use the splice member function with a different template. This function template needs four parameters. Parameter1 is the position in the container where the elements of myList are inserted; doub.begin() .Parameter2 is the list object myList containing the same type of objects as doub container.Parameters3 & 4 are iterators specifying a range of elements in myList. The elements in this range are moved to doub.begin() .Notice that the range includes all the elements between it1 and myList.end() the element pointed by it1 but not the one pointed by myList.end() as this points past the last element in the list.

Figure 203

Task 1Create a new project,call it List Find And Erase

Exercise 97 Create a list and list iterator . Load the file ListNumbers.txt to the list .

Exercise 98Use the find() 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);

November 2008 271 OUCS

Page 281: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 99 Add a number of your choice together with the returned iterator from find to the insert member function. The statement should be similar to myList.insert (it,value);

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

OUCS 272 November 2008

Page 282: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

23.9. Using the deque class containerThe deque 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 deque it is possible to use indexing to access individual elements for reading and writing in a similar way to that used with vectors.The deque 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 deques 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 insert and erase deque member function) but this is less efficient than using a list container.It is worth noting that unlike vectors, deques 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 deque will grow more efficiently than a vector (where large reallocations of memory are necessary as the vector grows) with its capacity managed automatically.The deque 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 vectors and deques provide a very similar interface and can be used for similar purposes, but internally both work in quite different ways.

November 2008 273 OUCS

Page 283: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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 1Open DequeAndIts file in the Deques and Iterators folder and examine the code to establish how to use the deque container.

Exercise 103Only parts of the code that relate to deques are covered. All other coding is covered in previous exercisesThe code shown in Figure 206 shows the use of deque member functions push_back and push_front 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 sort() algorithm, elements are sorted into ascending order.Class deque does not have a member function sort, but we can make use of the sort() alogorithm.myDeque.begin() and myDeque.end() return random-access iterators to the initial and final positions of the sequence to be sorted.

Figure 207

OUCS 274 November 2008

Page 284: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 105 Figure 208 shows how to use the insert() member function with deque . The deque 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 list container.

Figure 208

Exercise 106 Figure 209 shows the deletion of a deque element other than at the end of the container.myDeque.begin()+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 list .

Figure 209

November 2008 275 OUCS

Page 285: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 107 Examine the code in Figure 210. In this example we are using the insert function with a different number of parameters.The parameters here indicate where in the deque the elements will be inserted (it1) and the range of elements to be inserted myVec.begin() to myVec.end() .Note that the element pointed to by myVec.end() is not copied.

Figure 210

Task 1 Modify the program in DequeAndIts.dev so only the first two elements in myVec are copied to the deque.

OUCS 276 November 2008

Page 286: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

23.10. Using the multiset associative containerThe STL multiset class is used for the storage and retrieval of data from a collection in which the values of the elements contained need not be unique and in which they serve as the key values according to which data is automatically ordered . The key value of an element in a multiset may not be changed directly. Instead, old values must be deleted and elements with new values inserted. Note that unlike the multiset class, the set class is used for the storage and retrieval of data from a collection in which the values of the elements contained are unique and also serve as key values .

Exercise 108 Using the multiset container Learn how to structure and manipulate data in multiset containers

Task 1In eclipse, open the project MultiSet project file in the Multiset Container folder and examine the code to establish how to use the multiset container.

Exercise 109 The header file for multiset and set is the same and must be included to allow use of member functions, see Figure 211.

Figure 211

Exercise 110In Figure 212 the typedef keyword creates an alias called multSet for a multiset container data type.The effect of this statement is to sort the multiset from lowest to highest .

Figure 212

November 2008 277 OUCS

Page 287: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

typedefs 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 typedefs being created and used in declarations.

Figure 213

It is useful to define types when it is possible that the datatype 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 less<int> function object for less-than inequality comparison.less has its operator () member defined such that it returns true if its first argument compares lower than the second one using operator <, and false otherwise. The effect of "less" is to sort the multiset from lowest to highest .To sort from highest to lowest use "greater" function object.

Exercise 112 Figure 214 shows the count() member function being used to search the container for an element with a key of 15 .The function returns the number of times the element appears in container intMultiset .

OUCS 278 November 2008

Page 288: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 214

Exercise 113 Figure 215 shows the creation of constant iterator called result . The scope resolution operator :: is used to enable the name of the member that follows the operator (const_iterator) 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, bidirectional .

Figure 215

Exercise 114 Figure 216 shows the use of the find() member function which returns a bidirectional iterator.The function is used to search the container for an element with a value of 15 and return the iterator to it if found.If the value is not found an iterator to multiset::end() is returned. The end() iterator points to the element past the end of the container and it is possible to test for this.

Figure 216

November 2008 279 OUCS

Page 289: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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 insert member function to extend the container by adding all of array a elements. a and a + SIZE 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 lower_bound returns an iterator pointing to the first element in the container which does not compare less than 24 (using the container's comparison object, defined in typedef , in this case less).A pointer is returned to a value that is either equal to or greater than the key value, dereferenced here.

Figure 219

OUCS 280 November 2008

Page 290: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 118 Figure 220 shows upper_bound member function which returns an iterator pointing to the first element in the container which compares greater than the key, 24 (using the container's comparison object, less). Unlike lower_bound , this member function does not return an iterator to the element if it compares equal to 24, but only if it compares strictly greater.If the iterator is passed the container last element its equal to intMultiset.end() 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 pairs utility components. p represents a pair of const_iterators , in this case multSet const_iterators . The pair class couples together a pair of values, which may be of different types. The individual values are accessed through the public members first and second .

Figure 221

November 2008 281 OUCS

Page 291: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 120 Figure 222 shows the member function equal_range returning a pair of iterators, p.first and p.second.Member p.first is an iterator to the lower bound of the range with the same value as would be returned by lower_bound(key).p.second 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 lower_bound and upper_bound values.

Figure 222

Exercise 121 The values pointed at by the returned iterators are output using the dereference operator and the members as shown in Figure 223.

Figure 223

OUCS 282 November 2008

Page 292: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Task 1 Create a new project, call it MultiSetFind .

The program will import 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.See Figure 224.

Exercise 122 The class member functions you will need are find and erase . find returns an iterator and erase uses an iterator as an argument.

Figure 224

23.11. Using the multimap associative containerMultimaps and maps are both kinds of associative containers that are formed by the combination of a key value and a mapped value . Each container stores values with the associated key used to identify each element. Multimaps allow the use of duplicate keys , map containers do not have duplicate keys .The ordering of mutimap keys is done in a similar way as done with multiset by using a comparator function object . A multimap that uses integers as the key type can be sorted in ascending order with the function object less<int> .Many of the functions we have seen when using mutilist are also available for use with multimaps .

November 2008 283 OUCS

Page 293: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Exercise 123 Using the mutimap container Learn how to structure and manipulate data in multimap

containers

Task 1In eclipse, open the project Multimap in the MultiMap Container folder and examine the code to establish how to use the multimap container.

Exercise 124The header file for multimap and map is the same and must be included to allow use of member functions, see Figure 225.

Figure 225

Exercise 125 Figure 226 shows the creation of an instance of typedef multmap called cCardNo.

Figure 226

Exercise 126 In Figure 227 two value_type objects are inserted in cCardNo multimap. The values entered are integers and doubles for the key & value of the first two elements.value_type is a synonym for type as defined in the typedef for multimap at the start of the program, in this case the key is type int and the value type double .

Figure 227

OUCS 284 November 2008

Page 294: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Exercise 127 Figure 228 shows the use of a const_iterator named iter to run through cCardNo multimap using pointer notation to access members first and second . The iterator defined by multimap points to objects of value_type which are of type pair<const Key, Type> . The value of the Key is available through the first member pair and the value of Type of the mapped element is available through the second member of the pair.To dereference an iterator iter pointing to an element in a multimap we use the arrow -> operator.To access the value of the key for the element, use iter -> first which is equivalent to (*iter).first . To access the value of the mapped data for the element use iter -> second which is equivalent to (*Iter).second .

Figure 228

November 2008 285 OUCS

Page 295: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Task 1Create a new project,call it Credit Card .The program should read in the card numbers and transactions for the 50 customers detailed in cardNumbers.txt . There are 159 transactions by 50 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 Figure230 when run.

Exercise 128 Read all the records into a multimap using a while loop similar to Figure 229.

Figure 229

Figure 230

Exercise 129 Use the multimap count() member function in a for loop to total the number of transactions for each of the first twenty account holders, see Figure 231.

OUCS 286 November 2008

Page 296: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Figure 231

Exercise 130 Still inside the for loop add code similar to Figure 232.The function equal_range returns a pair, where its member pair::first is an iterator to the lower bound of the range (ex the first of many 1's).pair::second is an iterator to the upper bound of the range (ex the last of many 1's).indtotal is the sum of the mapped value for each transaction for each account.

Figure 232

November 2008 287 OUCS

Page 297: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

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

OUCS 288 November 2008

Page 298: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

23.12. More on using algorithmsAlgorithms do not work with containers themselves but rather with iterators . 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 unary predicates . These are functions that take a single parameter and return a Boolean value. A function object , or functor (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 bool is called a predicate , and a binary function (two arguments) whose return type is bool is called a Binary 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 predicate . 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 copy( ) algorithm called remove_copy_if( ) can meet the requirements.In C++ a functor 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 class type functor .Have a look at VecsAndIts project in the Algorithms and Predicates folder. Some of the available algorithms together with predicate functions are explained.Algorithms used in the program:

Operation Typeaccumulate algorithmassign member functionbinary_search algorithmcount_if algorithmfind_if algorithmincludes algorithmmax_element algorithmmin_element algorithmrandom_shuffle algorithmreplace algorithmreplace_copy algorithm

November 2008 289 OUCS

Page 299: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

replace_copy_if algorithm

Table 18

OUCS 290 November 2008

Page 300: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

24 Appendix24.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 assignment operator in C++ is =. The format is variable = expression; this can be read as, assign to the variable the value of the expression . An example to calculate the number of pence in a value in pounds would be:pence = pounds * 100;Note: it is easy to confuse the assignment operator = with the equals notation used in mathematics. The equals notation in C++ is ==.

Incrementing a variable.

November 2008 291 OUCS

Page 301: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

month = month + 1; adds the value one to the variable month. This can be written as month++;Decrementing a variable.month = month - 1; deducts the value one from the variable month. This can be written as month--;

In C++ it is also possible to combine arithmetic and assignment operations.

To add 2 to a variable total: total = total + 2; or total +=2;

To subtract 2 from total:total = total - 2; or total -=2;

To multiply total by 2:total = total * 2; or total *=2;

24.4. Relational and Equality Operators

The equality operator is used to compare two operands (a == b) and returns 1 (true) if both are equal, otherwise 0 (false) is returned.The inequality operator (!=) returns 1 (true) if both are NOT equal, otherwise 0 (false) 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 (true) if a is greater than or equal to b, otherwise 0 (false) is returned.

Standard algebraic equality or relational operator

C++ equality or relational operator

Sample C++ condition

Meaning of C++ condition

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

OUCS 292 November 2008

Page 302: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Standard algebraic equality or relational operator

C++ equality or relational operator

Sample C++ condition

Meaning of C++ condition

= == a == b a is equal to b!= a != b a is not equal to b

Table 19

November 2008 293 OUCS

Page 303: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

24.5. Logical OperatorsWhen using if 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 if statements but this can be a bit cumbersome.Logical Operators can be used to form more complex conditions by combining simple conditions.

Logical AND (&&) Operator allows a test to see if two conditions are true.if (leaveBooked > LeaveLeft && staffCover = = false)

cout<<”Take your holidays sometime else”;

Logical OR (||) Operator 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”;

Logical Negation (!) Operator 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 Sequence

Description

\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.

OUCS 294 November 2008

Page 304: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

\’ Single quote. Use to print a single quote character.

\” Double quote. Used to print a double quote character

24.7. Cast OperatorIs 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 OutputWhen 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. Note: setw must be specified for every item output.To use any stream manipulators you must include the header #include <iomanip>. setprecision is another manipulator and is used to set the precision of the next floating point number. Note: setprecision only has to be set once as the stream remembers the formatting directive and does not affect integer fields. The format is cout << setprecision(3) .To set precision for trailing zeros (0.100 will appear as 0.1) it is necessary to use the fixed format. The command is: cout << fixed; Note: fixed 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

November 2008 295 OUCS

Page 305: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Every program that you create will have at least one header file. If you use input or output you will have to include the iostream header.If you use mathematical functions you will need cmath. 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.

Standard C++ header Old headeriostream iostream.hiomanip iomanip.hfstream fstream.hcmath math.hcstdlib stdlib.hstring No equivalentvector 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 file scope . 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 block scope . 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 enum 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};

OUCS 296 November 2008

Page 306: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 DECEMBER is month number 12 .

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 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 const 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 Functions

Effect

at(element number) Gets the value contained in the specified element

back() Gets the value in the final elementbegin() Points to the first element in vectorclear() Erases the vectorempty() Returns true (1) if the vector is empty,

or false (0) otherwiseend() Points to the last element in vectorfront() Gets the value in the first elementpop_back Removes the final elementpush_back(value) Adds an element to the end of the

vector, containing the specified valuesize() Gets the number of elements

November 2008 297 OUCS

Page 307: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

24.14. Container global functions

Container global Functions Effectfind(); ptr = find(vec.begin(), vec.end(), 67);

Finds the element in the container containing number 67. Needs iterator (ptr) to store location of element.

reverse(); reverse(v.begin() v.end())

Reverses the values in a container (v)

sort(); sort(v.begin(), v.end())

Sorts the container (v)

24.15. cmath functions

Function Argument Result Returned Value

Example Result

ceil(x) double double Smallest integer ≥ x

ceil(2.1) 3.0

cos(x) double double Cosine of x radians

cos(1.0) 0.54

fabs(x) double double Absolute value of x

fabs(-1.5) 1.5

floor(x) double double Largest integer ≤ 2.9

floor(2.9) 2.0

pow(x,y) double double x to the yth power

pow(2,4) 16.0

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 radians

tan(1.0) 1.56

24.16. String class

The string class defines many member functions . A few of the basic ones are described below:

OUCS 298 November 2008

Page 308: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

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 object

string Intro = "Capetown";

string Mytown = "Boars"

string MyTown (Intro,4,5);

starts at character 4 ('t')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";

November 2008 299 OUCS

Page 309: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

string aName = "renna";

myName.replace (3,6,aName);

cout << myName << endl;

will produce an output “Sebrenna”

substr() Returns a substring of the current string.string myName = " Sebastion";

string aName = myName.substr (0,3);

cout << aName << endl;

will produce an output “Seb”

OUCS 300 November 2008

Page 310: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Non-member functions

getline()string name;

getline(cin, name);

24.17. Pointer based String Manipulation Functions

Function prototype Descriptionchar *strcpy(char *a1, const char *a2);

Copies the string a2 into the char array a1. The value of a1 is returned.

Example: strcpy(a1, a2); copy the contents of array a2 into array a1.Note: 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.

Example: strncpy(a1, a2, 10); copy the first 10 characters from array a2 into array a1.Note: 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.

Example: strcat(a1, a2); concatenate a2 to a1.Note: 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.

Example: strncat(a1, a2, 6); concatenate the first 6 characters of a2 to a1.Note: 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

November 2008 301 OUCS

Page 311: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Function prototype Descriptionterminate 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 array element 0 for each array and progresses through the array.

Example: 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.

Example: strcmp(a1, a2, 6); compares the first 6 characters in the two arrays.Note: 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.

Example: strlen(a1); gets the number of characters in array

OUCS 302 November 2008

Page 312: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Function prototype Description‘a1’.

Note: the above function prototypes are located in the header file <cstring> .

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 const to specify that an object is not modifiable and that any attempt to modify it will result in a compilation error. const Staff Peter(“12/8/78”,8,”OX34 7TY”); declares a const object Peter of class Staff and initialises the DOB , House No and post code .Declaring an object as const 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 const object will be caught at compile time rather than causing errors when the program executes.

24.19. ASCII Character set

Decimal Octal Hexadecimal Binary Value0 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)

November 2008 303 OUCS

Page 313: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Decimal Octal Hexadecimal Binary Value16 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)

30 36 01E 11110 RS(Request to Send)(Record Separator)

31 37 01F 11111 US (Unit Separator)32 40 20 100000 SP (Space)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 049 61 31 110001 150 62 32 110010 251 63 33 110011 352 64 34 110100 453 65 35 110101 554 66 36 110110 655 67 37 110111 756 70 38 111000 857 71 39 111001 958 72 03A 111010 : (colon)59 73 03B 111011 ; (semi-colon)

OUCS 304 November 2008

Page 314: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

C++ DPFE

Decimal Octal Hexadecimal Binary Value60 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 A66 102 42 1000010 B67 103 43 1000011 C68 104 44 1000100 D69 105 45 1000101 E70 106 46 1000110 F71 107 47 1000111 G72 110 48 1001000 H73 111 49 1001001 I74 112 04A 1001010 J75 113 04B 1001011 K76 114 04C 1001100 L77 115 04D 1001101 M78 116 04E 1001110 N79 117 04F 1001111 O80 120 50 1010000 P81 121 51 1010001 Q82 122 52 1010010 R83 123 53 1010011 S84 124 54 1010100 T85 125 55 1010101 U86 126 56 1010110 V87 127 57 1010111 W88 130 58 1011000 X89 131 59 1011001 Y90 132 05A 1011010 Z91 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 a98 142 62 1100010 b99 143 63 1100011 c

100 144 64 1100100 d101 145 65 1100101 e102 146 66 1100110 f103 147 67 1100111 g

November 2008 305 OUCS

Page 315: C++ Physics - University of Oxfordbrisbane/cpl…  · Web view · 2013-12-09The result being 2 remainder 3. C++ Operation C++ arithmetic operator Algebraic expression C++ expression

DPFE C++

Decimal Octal Hexadecimal Binary Value

104 150 68 1101000 h105 151 69 1101001 i106 152 06A 1101010 j107 153 06B 1101011 k108 154 06C 1101100 l109 155 06D 1101101 m110 156 06E 1101110 n111 157 06F 1101111 o112 160 70 1110000 p113 161 71 1110001 q114 162 72 1110010 r115 163 73 1110011 s116 164 74 1110100 t117 165 75 1110101 u118 166 76 1110110 v119 167 77 1110111 w120 170 78 1111000 x121 171 79 1111001 y122 172 07A 1111010 z123 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)

OUCS 306 November 2008