281
C++ Computer Programming Matthew Ryan & 母母母

C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Embed Size (px)

Citation preview

Page 1: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

C++ Computer Programming

Matthew Ryan & 母培新

Page 2: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

An Introduction

Why English? About the course About Matt

Page 3: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Why English?

Computing words are from English An international business Companies want English speakers A different style of teaching

Will talk slowly Will use simple words Lots of examples These notes are on the Internet

Page 4: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A different style of teaching

China is knowledge focused (learn this) How to write C++ program to do …

England is research focused (study this) Understand how to write any program

Chinese students work longer hours Expect to be told what to study

English students have less lectures Read more, write more, less direction

We will use a mixture of techniques Hope we can have some fun

Page 5: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A different style of teaching

China 1 course, 1 book

England No book / lots of books

Page 6: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Want to buy an English book?

You DON’T have to buy one

If you won’t or can’t read it thensave your money!

ISBN: 7-04-010038-X

Page 7: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Some rules

Come to the lectures! Try to read the notes before the lecture

www.mdryan.net Use the book(s) to “read around” the

subject Read the notes again later Understanding why is more important than

learning meaningless facts 70% exam, 30% coursework Think for yourself!

Page 8: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Course Content

Computer architecture English for computer programmers Procedural programming concepts Object Orientated Methodology The C++ standard template library Thinking skills

Page 9: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Timetable (Mr Mu’s group 2)

17 lecturesTuesdays 16:15 – 17:50 7503

(From 10/26)

7604

15 practicalsSaturday (10/9) 19:10 – 20:45

XS201_1Wednesdays 19:10 – 20:45 XS201_1

(from 10/13)

Plus independent study!

Page 10: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

About Matt

Matthew David Ryan Mr Ryan Matt马强

[email protected] www.mdryan.net

Page 11: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Qualifications BSc Joint Honors Degree Computer Science and Neuroscience

MSc (Masters) Degree Machine Perception and Neurocomputing

A variety of commercial programming experience

Mild British accent Teacher

Page 12: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

But why? Hobby

Exploring caves Caves

Made of limestone 50% in China Lots of new caves

China A great country Great people Too little money

exploring caves

Page 13: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

What is C++

C++ can be “Object Orientated” Describe objects (things) What to do with them

It is very fast and very powerful

C++ is EASIER than C

Page 14: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

New (English) words

Computer Program - source code (programmer sees)

Page 15: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

New (English) words

Computer Program - executable (user sees)

Page 16: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Computer Program

Source Code “Let me see the source” “Show me the code”

Compiler MS Visual C++, GCC, Borland Turbo C++ “Compile it” “Build it” (make, nmake)

Executable “Run it” The program

Page 17: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Computer Hardware

A programming course Just a quick tour Will be useful later

Memory Information Architecture

Page 18: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Binary System

Digital electronics – on or off Two values, enough to count,

0 1 10 (9 10 11 … 19 20) 11100 (99 100)101110111

Binary system (base 2) We normally use decimal system (base 10)

Page 19: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Hexadecimal system

Writing 11001101 00100100 01110010 represents what’s really stored in the computer but isn’t very convenient

Hexadecimal system (base 16) is closely related and much more convenientCD 24 72

16 = 2^4 Can use one base 16 number to represent

exactly 4 binary numbers Decimal system does not have this property

(10 is not a power of two) Less suitable for representing binary digits

Page 20: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Counting0000 0000 00 00000 0001 01 10000 0010 02 20000 0011 03 30000 0100 04 40000 0101 05 50000 0110 06 60000 0111 07 70000 1000 08 80000 1001 09 90000 1010 0A 100000 1011 0B 110000 1100 0C 120000 1101 0D 130000 1110 0E 140000 1111 0F 150001 0000 10 160001 0001 11 17

Page 21: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Computer memory

Each BIT of memory can be either on or off (1 or 0)

Group bits together and give them an address

Usually use groups of 8bits (one BYTE)

Access groups of bits by theiraddress

Page 22: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Lecture 2

Last week Introduction to the course and Matt Binary and Hexadecimal Systems Computer Memory

Today Representing information Running programs Writing programs

Page 23: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Representing information

Can use our groups of bits to store information Text Decimal numbers Pictures Sounds Computer programs

Page 24: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Storing Text Give each letter and symbol a code in the

binary systemH 100 1000 48e 110 0101 65l 110 1100 6Cl 110 1100 6Co 110 1111 6F

If everyone uses the same code then we can exchange messages

American Standard Code for Information Interchange (ASCII)

Defines 128 binary codes (7 bits) 95 characters, 33 control codes

Page 25: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

ASCII chart20: 30: 0 40: @ 50: P 60: ` 70: p21: ! 31: 1 41: A 51: Q 61: a 71: q22: " 32: 2 42: B 52: R 62: b 72: r23: # 33: 3 43: C 53: S 63: c 73: s24: $ 34: 4 44: D 54: T 64: d 74: t25: % 35: 5 45: E 55: U 65: e 75: u26: & 36: 6 46: F 56: V 66: f 76: v27: ' 37: 7 47: G 57: W 67: g 77: w28: ( 38: 8 48: H 58: X 68: h 78: x29: ) 39: 9 49: I 59: Y 69: i 79: y2A: * 3A: : 4A: J 5A: Z 6A: j 7A: z2B: + 3B: ; 4B: K 5B: [ 6B: k 7B: {2C: , 3C: < 4C: L 5C: \ 6C: l 7C: |2D: - 3D: = 4D: M 5D: ] 6D: m 7D: }2E: . 3E: > 4E: N 5E: ^ 6E: n 7E: ~2F: / 3F: ? 4F: O 5F: _ 6F: o

Page 26: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

An American code

What about us 95 characters (plus 33 control codes) Has S, e and $ but not ß, é, £ or €

ASCII uses 7 bits Can use an 8 bit code Keep first 128 characters the same, use

new 128 characters for own country 8-bit ASCII extensions Several standards for different regions

Page 27: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

What about Chinese? With 8 bits can still only represent 256

different characters Even I know more than 256 汉字 Simple solution is to use more bits 16 bits gives us 65536 characters

0000 FFFFUnicode (UTF16)

Can use 8 bit code and have a special character(s) to ‘escape out’ when we want to use more bitsGB2312, UTF8

Page 28: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

What about decimal numbers?

Want to work with numbers not just text

People don’t use binary (or hex) to count

0011 0001 (0x31) is ASCII for 1 Using 7 (or 8) bits to code only 10

numbers is wasteful This is really text and not a number in

the mathematical sense

Page 29: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Binary coded decimal

0000 0 0001 1 0010 2 0011 3 … … 1000 8 1001 90001 0000 100001 0001 11 … …0010 0000 20

Page 30: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Counting in base 2

BCD is still inefficient (waste A-F) Mathematics is complicated Why not just count in base 2 and

convert to decimal

Page 31: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Converting Binary to Decimal

Very simple system

0

Page 32: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

More numbers

What about negative numbers? Several systems Use one bit for the sign (+ or -) Commonly used system lets us use

mathematical ‘tricks’ to compute things faster (two’s complement notation)

What about real numbers?3.141592 Use one part to store 3141592 (mantissa),

another to store the position of the decimal point (exponent)

Similar to scientific notation (1.2345 x 1012) More bits lets us store more accurate numbers

Page 33: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Central Processing Unit The ‘brain’ of the machine Processor communicates with memory using

a “bus” Lots of parallel wires Each can transmit one bit (binary value) One for each bit of the address One for each bit of a memory cell Some to identify reading or writing, specify

timing, etc As well as main memory the processor has

several “registers” for work in progress Can transfer data from the main memory to

a register or back again

Page 34: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Machine Architecture

Page 35: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A simple program

Add two numbers Stored in two memory cells Store the results in a third cell

Sequence of instructions Copy from memory cell 1 to register A Copy from memory cell 2 to register B Add contents of register B to register A

storing result in register C Copy from register C to memory cell 3 Stop

Page 36: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Machine code Need to code these instructions for the computer Give each instruction a different binary code May also have binary parameters,

eg register number, memory cell address

Copy from memory cell 1 to register A 01 01 0A

Copy from memory cell 2 to register B 01 02 0B

Add contents of register B to register A storing result in register C

02 0B 0A 0C

Copy from register C to memory cell 3 03 0C 03

Stop 04

Whole program is,01 01 0A 01 02 0B 02 0B 0A 0C 03 0C 03 04

Page 37: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Stored program architecture

Program is just a binary sequence Can store in memory To run a program need to

Fetch the instruction from memory Decode the instruction Execute the instruction

• Repeat for next instruction… CPU has two special registers

Address of next instruction Code for current instruction

Page 38: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Writing programs Working out the binary code for a program

is, Slow and boring Easy to make mistakes Powerful

Can give every instruction a special English code,01 LOAD02 ADD03 STORE04 HALT

Can translate by hand Can get computer to translate the program for us

and store it in memory

Page 39: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Assembly

Program now more readable Still quite slow to write Still quite easy to make mistakes Still powerful

LOAD 01 0A Copy from memory cell 1 to register A

LOAD 02 0B Copy from memory cell 2 to register B

ADD 0B 0A 0C Add contents of register B to register A storing result in register C

STORE 0C 03 Copy from register C to memory cell 3

HALT Stop

Page 40: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

High Level languages

Computer can do more than just translate from one code to another

Why not let it translate one line into several symbols of machine codeset m03 = m01 + m02

Can support lots of new features to make our programs easier to write

Have a special program (a compiler) to convert to executable code

Page 41: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

C and C++

C is a high level language designed to be, Much easier to understand than assembler As powerful As fast “Close to the machine” portable

C++ is the “next generation” New features for writing programs Especially object orientated features

C and C++ compilers are very advanced pieces of software

Page 42: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Libraries and Modules

Don’t want to rewrite code someone else has already written Expensive Might make mistakes User gets confused Need to share resources with other programs

Compile each source file Link with other compiled source files and

libraries Now can execute our program C++ is easy, learning how to use the

libraries is harder!

Page 43: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Lecture 3

Monday Storing information

• Text• Different systems

• Numbers• Different systems• Different types of numbers

• Signed / unsigned• Integer / real

Computer Architecture• Bus• Registers• Stored Programs

• Fetch, Decode, Execute cycle

Page 44: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Lecture 3

Monday (continued) Programs

• Machine code• Assembly code• High Level Languages• Compiling and Linking

• Compile source files to object (machine) code• Link object code together• Can now be loaded by operating system

• Need for libraries

Page 45: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Lecture 3

Today IDEs Visual C++ Writing our own programs Words for parts of programs

Page 46: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

IDE

Integrated Development Environment All in one system for developing programs Can edit, compile, link and execute our

programs all from the comfort of our IDE Underlying system is exactly the same

Page 47: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Visual C++ Summary

Powerful and fast Complicated One of many compilers for C++ Best compiler for Windows programs (?) Source files (.cpp, .c, .h, .rc)

The files which do the work of the program Projects (win32 console application)

Manage the source files Help us to compile and build the program

Workspaces Manage the projects, layout of windows etc

Page 48: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Window Names

Output Window

Workspace Window

menu

Page 49: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

age.cpp

#include <iostream>using namespace std;

int main(){ int age=26; cout << "I am " << age << " years old" << endl; age++; /* add one */ cout << "Next year I will be " << age << endl; return 0;}

Page 50: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

age.exe

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ gcc age.cpp -o age

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ age

I am 26 years old

Next year I will be 27

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$

Page 51: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Statements

Instructions Finish with a ‘;’

(semicolon)

#include <iostream>using namespaceusing namespace std;std;

int main(){ intint age=26; age=26; cout << cout << "I am ""I am " << << ageage << << "" years old"years old" << endl<< endl;; age++;age++; /* add one */ coutcout << << ""Next year I will beNext year I will be " " <<<< age age << endl<< endl;; returnreturn 0;0;}

Page 52: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Statement Block

List of instructions Everything between ‘{’ and ‘}’

(curly brackets, braces)

#include <iostream>using namespace std;

int main(){{ intint age=26; age=26; cout << cout << "I am ""I am " << << ageage << << "" years old"years old" << endl<< endl;; age++; age++; /* add one *//* add one */ cout << cout << ""Next year I will beNext year I will be " " << << age age << endl<< endl;; returnreturn 0; 0;}}

Page 53: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Statement Block

List of instructions Everything between ‘{’ and ‘}’

(curly brackets, braces)

...

if (age<18) /* cannot be a student here */

{{

printfprintf(("Error, too young to be a student here""Error, too young to be a student here"));;

exitexit((11));;

}}

...

Page 54: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Functions

Building blocks of a C program Also part of C++ programs

main(), printf(), exit(), …

#include <iostream>using namespace std;

intint mainmain(()){{ int age=26; cout << "I am " << age << " years old" << endl; age++; /* add one */ cout << "Next year I will be " << age << endl; return 0;}}

Page 55: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Functions

Building blocks of a C program Also part of C++ programs

main(), printf(), exit(), …

#include <stdio.h>

void void mainmain((voidvoid))

{{

int age=26;

printf("I am %d years old\n", age);

age++; /* add one */

printfprintf(("Next year I will be %d\n", age));

}}

Page 56: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Keywords char, int, float, void, signed, if, while, case, else class, public, friend, this, operator, new, true

Highlighted in blue by text editor

#include <iostream>using namespaceusing namespace std;

intint main(){ intint age=26; cout << "I am " << age << " years old" << endl; age++; /* add one */ cout << "Next year I will be " << age << endl; returnreturn 0;}

Page 57: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Keywords

10,000+ words in English <100 words in C++

auto, break, case, catch, char, class, const, continue, default, do, double, else, enum,

extern,float, for, friend, goto, if, inline, int, long, new,private, protected, public, register, return, short,signed, sizeof, static, struct, switch, throw, try,typedef, union, unsigned, void, volatile, while

Page 58: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Data Types

int, float, void, unsigned int, long, double, char string, list, …

Ways to represent information

#include <iostream>using namespace std;

intint main(){ intint age=26; cout << "I am " << age << " years old" << endl; age++; /* add one */ cout << "Next year I will be " << age << endl; return 0;}

Page 59: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Identifiers

Variable names and object names age, height, i, j, x, y, cout

Also function names main, printf

#include <iostream>using namespace stdstd;

int mainmain(){ int ageage=26; coutcout << "I am " << ageage << " years old" << endlendl; ageage++; /* add one */ coutcout << "Next year I will be " << ageage << endlendl; return 0;}

Page 60: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Operators + - * / += ++ = == > != >= ! && || <<

a+b a+1 a=b+c a=a+3 if(a==7) … if(a==7)||(a==8) … cout << age

#include <iostream>using namespace std;

int main(){ int age==26; cout <<<< "I am " <<<< age <<<< " years old" <<<< endl; age++++; /* add one */ cout <<<< "Next year I will be " <<<< age <<<< endl; return 0;}

Page 61: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

English Summary

Functions Statements Statement Block Keywords Data Types Identifiers

Variable names Function names

Operators

Page 62: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

New C++ features

Object Orientated Datatypes Classes Variables Objects

A library of standard classes string, cout, vector

Lots more…

Page 63: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Classes

Programmers own data types Information and operations Example

int Information:

a whole number (-2147483648 to 2147483647)

Operations: a+b, a++, a+=b, a*b, a/b, … a=b, a==b

Page 64: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

string class

Simpler to use C: char *str[]; C++: std::string str;

Information: A sequence of characters eg “Hello”

Operations: =, +, +=, ==, …

Provided by the standard c++ library #include <string> std::

• using namespace std;

Page 65: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

strings.cpp#include <string>#include <iostream>

int main(void) { std::string s1 = "Hello World"; std::string s2 = "Hello"; std::string s3 = " World";

s2 += s3;

if(s1 == s2) { std::cout << "LOOK - EASY!!!” << std::endl; return(0); } else { std::cout << "Oops!" << std::endl; return(1); }}

Page 66: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

strings.exe

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ g++ strings.cpp -o strings

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ strings

LOOK - EASY!!!

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$

Page 67: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cout object

Easier to use printf(“Hello %s”, name); cout << “Hello” << name;

Information Everything about controlling the screen

Operations << (output operator) Many formatting operations

Provided by the standard C++ library #include <iostream> std::

Page 68: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cout.cpp#include <string>#include <iostream>

int main(void){ std::string s1 = "Hello World\n"; std::cout << s1;std::cout << "Hello again" << std::endl;

}

Page 69: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cout.exe

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ g++ cout.cpp -o cout

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$ cout

Hello World

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course

$

Page 70: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cin object

Easier to use scanf("%s", name); cin >> name

Information Everything about the keyboard

Operations >> (input operator)

Provided by the standard C++ library #include <iostream> std::

Page 71: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cin.cpp

#include <string>

#include <iostream>

using namespace std; // avoid writing std::

int main(void)

{

string s1;

cout << "Please type your name: ";

cin >> s1;

cout << "Hello "

<< s1

<< '\n';

}

Page 72: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

cin.exe

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course$ g++ cin.cpp -o cin

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course$ cinPlease type your name: MattHello Matt

matt@MATT-LAPTOP /d/My Documents/matt/Cpp Programming Course$

Page 73: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

English Summary

Functions (main, printf) Statements (int i=7;) Statement Block ({}) Keywords (int, using, if) Data Types (int, float) Identifiers

Variable names (age, height, x, y) Function names (main, printf)

Operators ( + - ++ << )

Page 74: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

C++ Summary

Object Orientated Programming C++ Programming is easier than C string class cin and cout objects endl object

Page 75: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise 1.1 (source)#include <iostream>#include <string>using namespace std;

int main() { string user_name; cout << "Please enter your name: "; cin >> user_name; cout << endl << "Hello, " << user_name << "... and goodbye!" << endl; return 0;}

Page 76: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise 1.2a

Break the program

...int main() { string user_name; ...

...int main() { //string user_name; ...

After:

Before:

Page 77: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Undeclared Identifiers

error C2065: 'user_name' : undeclared identifier

when we try to use "user_name" with cin and cout we find nothing has "declared" the object

Page 78: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring objects

What class of object ? string, int, float

What identifier will we use ? username, age, height

Do we want to initialize it ? "Matt", 26, 1.75

Page 79: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaration statements

int age;string user_name;float height, weight;

int age=26;string user_name="Matt";float height=1.75, weight=122.5;

Page 80: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Multiple values

An object might store more than one piece of information

For a new cup might need colour, size, drink

cup c1("red", 500, "coffee");int age(26);string user_name("Matt");float height(1.75), weight(122.5);

Page 81: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise 1.2

Break the program!

#include <iostream>#include <string>using namespace std;...

//#include <iostream>#include <string>using namespace std;...

After:

Before:

Page 82: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

#include <...>

Commands starting with a hash ('#') are "Preprocessor Directives" Things to do before compiling

#include "includes" the contents of another file

<iostream> declares the cout, cin and endl objects If you do not include it you cannot use these

objects or anything else "declared" in this file <string> declares the string class

Page 83: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise 1.3

Break the program!

...int main() { string user_name;...

...int my_main() { string user_name;...

After:

Before:

Page 84: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

int main()

Every C++ program has at least one function

One function is 'called' when the program is run

For C++ programs using the console this function must be called main

No main function nothing to run cannot build the program

• Link time error – file compiles OK but cannot make

Page 85: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Common errors

Undeclared objects Forget to declare Spelling errors Namespace errors (std::)

Forgetting the semicolon (;) Using Chinese punctuation

{…} (…) […] <…> "…" '…' ? ! : ; Project errors

Page 86: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Flow Control

How the computer moves through the program

Many keywords are for "flow control"

int, float, double, char,break, case, continue, default, do, else, for,goto, if, return, switch, while

Page 87: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Normal flow

Statement 1;

Statement 2;

Statement 3;

Statement 4;

Page 88: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if

if (expression) something

...if (height<1.4) price*=0.7;...

If height is less than 1.4 then set price to be 70%

If height is not less than 1.4 then do not change price

Page 89: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if flow

Condititional Statementif(…)true

false

Page 90: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if else

if (expression) somethingelse other thing

if (height<1.4) price=30;else price=50;

If height is less than 1.4set price to be 30

else set the price to be 50

Page 91: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if else flow

Condititional Statementif(…)

else Statement

truefalse

Page 92: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Statement Blocks

Can also use statement blocks ({…})

if (height < 1.4){ price=30; type="child";}else{ price=50; type="adult";}

Page 93: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Nested if statements

if (height<0.6) {price=0;

}else { if (height<1.4) price=30; else price=50;}

Page 94: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Nested if flow

Condititional Statement 2else if

else if Condititional Statement 3

Else Statement

Condititional Statement 1if true

true

true

false

false

false

Page 95: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

goto

"Go to" part of a program

Not recommended!

if (height < 0) goto error;.........error:cout << "Error !"

Page 96: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

switch statement

Like the goto statement but more structured Structure is good - less confusing So the switch statement is better than

goto ! Similar to if-elseif-elseif-else but a little

simpler

Page 97: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Switch statementswitch(price) {case 0:

type="baby";break;

case 30:type="child";break;

case 50:type="adult";break;

default:type="unknown";

}

Page 98: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

switch flow

Condititional Statement 2case 2

case 3 Condititional Statement 3

Condititional Statement 1case 1

switch

Page 99: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Branching Flow Control

if if else nested if (if – else if – else if – else) (goto) switch

Page 100: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Conditional Statements

if if else nested if (if – else if – else if – else) statement blocks ({…}) (goto) switch (case, default, break)

Page 101: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Normal flow

Statement 1;

Statement 2;

Statement 3;

Statement 4;

Page 102: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if

if (a) b; If a is true then do b

...if (height<1.4) price*=0.7;...

Page 103: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

if else

if (a) b; else c; If a is true then do b else do c

if (height<1.4) price=30;else price=50;

Page 104: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Nested if statements

if (height<0.6) price=0;else if (height<1.4) price=30;else price=50;

if (a) b; else if (c) d; else e; If a is true then do b, otherwise if c

is true then do d, otherwise do e

Page 105: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

switch statement

switch(price) { case 0: type="baby"; break; case 30: type="child"; break; case 50: type="adult"; break; default: type="unknown";}

switch (a) { case b: … case c: … } Go to the case which matches a or

default: if there is no match

Page 106: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

while loop

while (expression) something

while (guess!=age){

cout << "Guess my age: ";cin >> guess;

}

Page 107: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

while flow

Condititional Statementswhile(…)true

false

Page 108: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

do loop

do something while (expression) Similar to the while loop Check is at end of loop not the start Middle always runs once

do {cout << "Guess my age: ";cin >> guess;

} while (guess!=age);

Page 109: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

do flow

condititional statements

while(…)true

false

do

Page 110: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

break statement

Goes straight to the end of a do, while or for loop or a switch statement block,

while (guess!=age){

cout << "Guess my age: ";cin >> guess;if (guess==0) break;

}

Page 111: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

continue statement

Goes straight back to the start of a do, while or for loop,

while (guess!=age) {

cout << "Guess my age: ";cin >> guess;if (guess==0) continue;......

}

Page 112: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise

Draw a flowchart and then write a program to play "Guess my age"

matt@LAPTOP$ guess_ageguess_age

Guess my age: 2727Too high! Guess my age: 2525Too low! Guess my age: 2626

Well done – that took you 3 tries.

Page 113: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

for loop

Most used – most complicated Normally used for counting Four parts

Initialise expression Test expression Body Increment expression

Page 114: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

for loop

body statements

continuationtest

initialisation

increment

true

false

Page 115: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

for loop

int count;

for (count=1; count<=10; count++)

{

cout << count

<< " squared is "

<< (count*count)

<< '\n';

}

Page 116: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise

Draw a flowchart and then write a program to find the value of one number raised to power of another

matt@LAPTOP$ powerpower

Enter base: 66Enter exponent: 44

6^4 = 6x6x6x6 = 1296

Page 117: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Flow control summary

branching if if-else nested if (goto) switch

looping while do-while for

Page 118: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Flow Control

Branching statements if else goto switch case default break

Looping statements while do for break continue

Function statements return

Error control statements try catch throw

Page 119: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Makes programs easier to understand Maximum of one statement per line Indent the body of functions, conditional

statements and loops Choose meaningful identifiers

int age, height; NOT int a, h; KISS: Keep It Simple, Stupid Use comments // ... Lots of different 'standard' styles MSVC will format code for you

Formatting programs

Page 120: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Why use namespaces?

Use 'libraries' from other programmers

#include <iostream> // use the iostream library

There are not enough good names for functions and variables

What if two libraries use the same function names?

Page 121: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Namespaces

A namespace lets us distinguish between two names from different places

In C++ the standard library is in the std namespace

Things in no namespace are said to be in the Global NamespaceGlobal Namespace

Page 122: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

How to use a namespace

std::cout << "Hello"; Specify that this cout object is from the

std namespace

using namespace std; Copy everything from the std

namespace into the global namespace

using std::cout; Copy cout from the std namespace into

the global namespace

Page 123: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

What about <iostream.h>

Very similar to <iostream> Also declares cin, cout and endl

In the global namespace not in the std namespace

This is for compatibility with older versions of C++

Page 124: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

The C standard library

All the standard C libraries can also be used from C++

printf() is declared in <stdio.h> std::printf() is in <cstdio> <stdio.h> is the C version or the

'backwards compatible' version <cstdio> is the C++ version

Page 125: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

return(0) in int main()

When a function returns a value it is given to the function that calls it

When main returns a value it is given to the operating system (Windows)

main (should) always return an int

Page 126: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

What should we return?

number is usually ignored by windows 0 means success greater than 0 means an error maybe a different number for a different

error if declare our function as int and

don't use return will get a warning from the compiler

Page 127: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

void datatype

Special data type to represent nothing or an unknown type of data

int main(void) main function expects nothing Exactly the same as int main()

void main() main function returns nothing In C++ main() should always return an int

More uses of void coming later…

Page 128: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pre and post increment

What's the difference between i++ and ++i ?

a=i++; a=i; i=i+1; i++ gives the value of i then adds one Post-increment

a=++i; i=i+1; a=i; ++i adds one and then gives the value Pre-increment

Page 129: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Arrays

An array is a sequence of data 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89

is a sequence of ints "Matthew", "Mark", "Luke", "John"

is a sequence of strings

int fibonacci[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};

string books[] = {"Matthew", "Mark", "Luke", "John"};

Page 130: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring Arrays

Class of data int, float, string Identifier ages, heights Subscript operator [ ] (square brackets)

Size (length) 10 Initial values {1, 1, 2, 3, 5, 8}

int ages[10];int fibonacci[] = {1, 1, 2, 3, 5, 8};string books[] = {"Matthew", "Mark"};int numbers[8] = {1, 1, 2, 3, 5}

Page 131: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Accessing Arrays

We access elementselements of an arraywith the array's identifier and the subscript operatorsubscript operator []

Array elements count from zerozero (0)cout << "Book 0 is " << books[0] << '\n';cout << "Book 3 is " << books[3] << '\n';

for (int e=0; e<11; e++){ // use elements 0-10cout << "Element " << e << " is "

<< fibonacci[e] << endl;}

Page 132: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

matt@LAPTOP$ arraysarrays Book 0 is MatthewBook 3 is JohnElement 0 is 1Element 1 is 1Element 2 is 2Element 3 is 3Element 4 is 5Element 5 is 8Element 6 is 13Element 7 is 21Element 8 is 34Element 9 is 55Element 10 is 89

Page 133: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

for loop

print e and element at e

is e<11

e=0

e++

yes

no

There are 11 elements, 0 to 10

Page 134: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Setting Array Elements

We can set the value of an array element the same way

fibonacci[0]=1;

cout << fibonacci[0];

We get the value of an array element with the subscript operator

Page 135: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Fibonacci source#include <string>#include <iostream>

using namespace std;int main(){

const int max=30;unsigned long int fib[max] = {1,1};

for (int n=2; n<max; n++){

fib[n] = fib[n-1] + fib[n-2];cout << "fibonacci(" << n << ") = "

<< fib[n] << '\n';}

}

Page 136: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Fibonacci outputmatt@LAPTOP$ fibonaccifibonaccifibonacci(2) = 2fibonacci(3) = 3fibonacci(4) = 5fibonacci(5) = 8fibonacci(6) = 13fibonacci(7) = 21fibonacci(8) = 34......fibonacci(24) = 75025fibonacci(25) = 121393fibonacci(26) = 196418fibonacci(27) = 317811fibonacci(28) = 514229fibonacci(29) = 832040

Page 137: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

C style strings

In C there is no string class Use an array of type char

char s1[25] = {'H','e','l','l','o','\0'};

char s2[25] = "Hello";

Ends with the special '\0' character– don't need to remember the length

Causes a LOT of problems in programs – use the string class!

Page 138: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exercise

Write a program to store and display the marks of ten students

matt@LAPTOP$ marksmarks

Student 0=0, 1=0, 2=0, 3=0, 4=0, 5=0, 6=0, 7=0, 8=0, 9=0Enter student number to change mark: 4Current mark is 0 enter new mark: 5

Student 0=0, 1=0, 2=0, 3=0, 4=5, 5=0, 6=0, 7=0, 8=0, 9=0Enter student number to change mark: 1Current mark is 0 enter new mark: 6

Page 139: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Problems with arrays

Need to remember the size Cannot change the size "Off by one" error Arrays are one of the biggest sources

of errors in programs Don’t even try to think about 2D

arrays (arrays of arrays!) In C a string is an array of chars so an

array of C style strings can be a 2D array (a string table)

Page 140: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Functions

answer = function_name(arg1, arg2) Can give 0 or 1 answers Can take 0 or more arguments (parameters) We can return an answer then ignore it

cout << "Enter height: ";cin >> height;price = ticket_price(height);cout << "Your ticket will cost: "

<< price << '\n';

Page 141: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Writing Functions

Class of the answer (return type) Name of the function (identifier) Classes and names of arguments

(parameter list) A statement block to do the work (body)

float ticket_price (float h){

float tp = 50;if (h < 1.4) tp *= 0.8;return(tp);

}

Page 142: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring functions

We must declare our functions before using them Class of the function (return type) Name of the function (identifier) Classes of arguments of the function

string user_name;float ticket_price(float);

string user_name;float ticket_price(float height);

Page 143: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declare Functions

int get_id(int);

Return class int, float, void, string

Function identifier main(), printf()

Argument classes int, float, void, string

(Argument names) int max, float height

Similar to declaring objects

Page 144: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Writing functions

int get_id(int max){ ...}

Return class int, float, void, string

Function identifier main(), printf()

Argument classes int, float, void, string

Argument names int max, float height

Function body { ... }

Page 145: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Function Flow

Statement 1;

Statement 2;

function(…)

Statement 4;

Statement 1;

Statement 2;

Statement 3;

Statement 4;

main() function()

Page 146: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using Functions

Objects in functions usually get destroyed between calls,

void change(){int i=1;cout << i;i = i + 1;

}

change(); // prints 1change(); // still prints 1

Page 147: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Static Data

Can have data remember value between functions,

void change(){static int i=1;cout << i;i = i + 1;

}

change(); // prints 1change(); // now prints 2

Page 148: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using Functions

Objects get copied during function calls Copies get destroyed at end of function

int main(){void change(int);int x = 1;change(x);cout << x; // prints 1

}void change(int i){ i = i + 1; }

Page 149: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Global Data and Functions

Can have data and functions accessible to all functions in file,

#include <iostream>using namespace std;

int main(){int i; // localint function();... }

int function(){...}

#include <iostream>using namespace std;

int i; // globalint function();

int main(){...}

int function(){...}

Page 150: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using functions

Arguments are passed BY VALUEint get_mark(int stuid);int id=4, mark;

mark = get_mark(id);mark = get_mark(4);

Function cannot change value of stuid – it is given a COPY of this variable

Page 151: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Local and Global scope

Objects and Functions can be declared inside functions (local scope) outside functions (file or global scope)

int x; // globalint main(){

int y; // local}

Page 152: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Static data

Local data is lost between calls,void add_student(int id, string name){

int total_students;total_students++;...

}

Static local data is maintained,void add_student(int id, string name){

static int total_students;total_students++;...

}

Page 153: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Recursive Functions

A function which calls itself is a recursive function e.g. factorial numbers

5! = 5x4x3x2x16! = 6x5!1! = 1

int factorial(int n){

if (n==1) return (1)return(n * factorial(n-1));

}

Page 154: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Default Values

A function may provide default values for some or all of it's arguments

void get_mark(int stuid=0); Defaults can be given

When function is declared When function is written NOT BOTH

If some parameters have no default value these must be on the left

void add_stu(int id, string name="unknown");

Page 155: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Overloaded functions

There can be more than one function of the same name in the same namespace - if they have different argumentsvoid print_number(float);

void print_number(int); Compiler chooses correct function

Page 156: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Multiple source files

Group related functions together in files

Have a common 'header' file declaring them

Other files which want to use these functions just include this header file

Separate components are combined at link time

Be careful not to declare things twice

Page 157: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Thinking about errors

What if a user enters the wrong value and a function can't operate correctly?

Should test all objects to make sure they are valid

How do we indicate failure? Can only return one value

Return special value for errors (eg 0 or -1) Return true if successful, false otherwise and

use a pointer parameter to set a value. Throw an exception if cannot succeed.

Page 158: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Structured Programming

Makes writing and maintaining programs much simpler and faster

Do not use Do not use the goto statement! Do useDo use functions Separate your program into different

tasks for different things

Page 159: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Structured Data

Computer programs are tools for manipulating information.

CS101:data+structure=information

Data: int, float, string, int* The struct keyword Lets us structure our data

Page 160: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

struct

struct student{int id;string name;int mark;

};

Groups data types together Yet another use of brackets! Don't forget the last semicolon

Page 161: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using structures

Use 'student' like other datatypes Access members with the

member selection operatormember selection operator '.' (dot)

student s1;s1.id = 1234567;s1.name = "Matt";s1.mark = 89;cout << "student: " << s1.id << endl << " name: " << s1.name << endl << " mark: " << s1.mark << endl;

Page 162: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Structured programming

Computer programs are operations on information

Operations are functions Information is structured data Our programs model the way the

computer works

Page 163: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Computer Memory

Variables and objects are stored in memory

C++ helps a LOT with managing this memory – it is much simpler than C

We still need to know a little bit about it though

Need to know about hexadecimal numbers (hex, base 16)

1,2,…,8,9,10,11,12,13,14,15,16,17,… ,20,21,22,…,255

1,2,…,8,9, A, B, C, D, E, F,10,11,… ,14,15,16,…, FF

Page 164: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Data in memoryad

dre

ssd

ata

Memory does not know what it stores Must use enough memory for what we want to store

One reason for lots of problems with arrays Each "cell" stores just one byte

'H' 'e' 'l' 'l' 13 0 0 311 0 Hello'o'

001000

001001

001002

001003

001004

001005

001006

001007

001008

001009

00100A

00100B

00100C

00100D

00100E

001010

001011

001012

00100F

Page 165: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Size of a datatype

Can find how much memory a datatype or object needs with the 'sizeof' operator,

cout << sizeof(int); // 4

int i = 0;cout << sizeof(i); // 4

cout << sizeof(char); // 1

int a[10];cout << sizeof(a); // 40 = 4 x 10

Page 166: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Address of an object

Can find the address of an object using the address-of operator, '&' (ampersand)

String s1="Hello World";

cout << &s1;

matt@LAPTOP

$ addressof

0x76fde0

Page 167: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers

What if we want to store the address? A pointer is a special datatype that

stores an address

add

ress

001000

001001

001002

001003

001004

001005

001006

001007

001008

001009

00100A

00100B

00100C

00100D

00100E

00100F

001010

001011

001012

'H' 'e' 'l' 'l' 13 0 0 311 0 001009

data 'o' 001000

Page 168: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring pointers

We need Identifier What class of data we point to Something to point to

int i1=26; int* ptr1 = &i1;string s1 = "Hello";string* ptr2 = &s1;void* ptr2a = &s1;float* ptr3; // badfloat* ptr4=0; // better

Page 169: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using pointers

Can find the value at an address using the value-of operator, * (asterisk)

cout << ptr1; // 0x........

cout << *ptr1; // 26

WARNING!Be careful to initialise pointers before trying to use them

Page 170: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers Summary

'size of' operator sizeof(i) 'address of' operator &i pointer datatypes int* p1 value of (dereference) *p1 null pointers p1=0

Page 171: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Constant pointers

Data we don't want to change in the program is declared as a constantconst float pi = 3.141592;const int max = 10;

If declare pointer as a constant we cannot change the address stored – but we can change the information at that addressint i1=26, i2=28;const int* ptr = &i1;ptr = &i2; // errori1=27;*ptr = 29;

Page 172: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers and arrays

An array variable is really just a (const) pointer to the first value of the array,

int a[10] = {2,4,8,16,32,64,128,256,512,1024};

cout << &a[0]; // 0x...cout << a; // Ox...

cout << a[0]; // 2cout << *a; // 2

Page 173: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers to structures

Pointers to structures can use the pointer member selection operator, '->' (pronounced as 's ?)

student* s2 = &s1;(*s2).name = "Ma";cout << (*s2).name << endl;s2->name = "Liu";cout << s2->name << endl;

Page 174: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointer arithmetic

When we add one to the value of a pointer, we actually add the size of the data-type it points to,

int i;int* p = &i;int* q = p+1;

cout << p; // eg 0x0063FDF8cout << q; // eg Ox0063FDFC

cout << sizeof(i); // 4cout << q - p; // 1

Page 175: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using pointer arithmetic

Pointer addition can be used with arrays Since a is a pointer to a[0], a+1 is a

pointer to a[1] We cannot change the value of an array

pointer (no a=a+1 or a++)

int a[10] = {2,4,8,16,32,64,128,256,512,1024};int* sentinel = &a[10]; // or a+10;for (int* index=a; index<sentinel; index++)

cout << *index << endl;

Page 176: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Sentinel Values

When passing an array we are really passing address of first value

void print_marks(int marks[], int max)

void print_marks(int* start, int* sentinel){

for(int* i=start; i<sentinel; i++)cout << *i << endl;

}

Rather than pass the size of the array could pass a sentinel value

Page 177: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers to pointers

A pointer is an object which stores an address

The pointer object is stored in memory

So can have a second pointer to it

00100D

add

ress

001000

001001

001002

001003

001004

001005

001006

001007

001008

001009

00100A

00100B

00100C

00100D

00100E

00100F

001010

001011

001012

311 001009

data

Page 178: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using double pointers

int age = 26; // intint* p1 = &age; // pointer to intint** p2 = &p1; // pointer to pointer to int

cout << age; // agecout << *p1; // value at p1cout << **p2; // value at value at p2

Could have an array of pointers and use pointer arithmetic to walk the array

Page 179: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Pointers to functions

A function is also stored in memory Can have a pointer to a function

int compare(int a, int b);int (* p1) (int, int) = &compare;

Why the extra brackets? What about functions that return

pointers?int* compare(int a, int b);

a function returning a pointer? or a pointer to a function?

Page 180: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Qsort example

The standard c library provides a function to sort an array of anything Pointer to the first element of the array Number of elements in array Size of each element Pointer to a function which compares

two elements

Page 181: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Comparing two elements

Function is given two pointers to elements and must return 0 if elements are same less than 0 if 1st is less than 2nd

more than 0 if 1st is more than 2nd

int comp(const void *left, const void *right) {int i1 = *(int*)left;int i2 = *(int*)right;if (i1==i2) return(0);if (i1<i2) return(-1);if (i1>i2) return(1);

}

Page 182: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

float and double datatypes

Both store "floating point" numbers pi = 3.141592 Store number and position of decimal point (.)

A double data type is more accurate ("double precision") but takes up more memory space.

Computers prefer integers int, long, short, char

Page 183: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Conversion warnings

warning C4305: 'initializing' : truncation from 'const double' to 'float'

In C / C++ a literal floating point number is normally assumed to be of type double

Might loose precision (accuracy) if convert from a double to a float

float pi = 3.141592;

float pi = 3.141592f;

double pi = 3.141592;

Page 184: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Converting values

Can force a conversion from one datatype to another with the cast operator

float f1;int i1;i1 = f1; // errori1 = (int) f1;void* p1 = &i1;cout << *p1; // errorcout << *(int*)p1;

Page 185: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Object Orientated Programming

The real world is made from "things" Things have both information and

operations (properties and methods) Group information and operations on

information together Objects Use these objects to model things in the

world instead of things in the computer Lots of objects are similar Classes of objects

Page 186: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A class for cars

Operations: Drive forward Turn left Turn right

Information: Position Direction facing

Page 187: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

class keyword

Used for declaring a new class Similar to the struct keyword

class car{

void drive_forward();void turn_left();void turn_right();string color;struct{int x; int y;} pos;enum{north, south, east, west} heading;

};

Page 188: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Enumerations

How to store the direction? One way is to use an integer,

1=north, 2=east, 3=south, 4=west An enumeration is a special type of integer

that lets us give names to numbersenum direction{

north = 1,east = 2,south = 3,west = 4

};direction d = north;

Page 189: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Access modifiers

Normally only functions that are also declared in a class can use functions and objects declared in that class

Private access modifier, private: To allow other classes and global functions

to use functions from a class we must make them public

Public access modifier, public: The only difference between the struct and

class keywords is that classes have private members by default

Page 190: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Public cars Others can drive the car and see it's position

and direction - but only the car knows how to change it's position

class car{public:

void drive_forward();void turn_left();void turn_right();int get_x();int get_y();char get_symbol();

private:struct{int x; int y;} pos;enum{north, south, east, west} heading;

};

Page 191: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Scope operator ::

As used with namespaces,std::cout << "Hello World";

To define and use functions from a class we also use the scope operator

void car::drive_forward()

{

if(heading==east) pos.x++;

if(heading==west) pos.x--;

// ...

}

Page 192: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Objects and Classes

What happens when we make a new car?

my_int is a variable of type int my_car is an object of class car

int my_int;

car my_car;

Page 193: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Constructors

To initialise a new int we can write either

int my_int=7;or

int my_int(7); How do we do this for a new object? A constructor is a special public

function used to initialise objects

Page 194: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring constructors

Same name as class No return type Must be public

class car{public:

car(int x, int y);car();void drive_forward();void turn_left();// ...

};

Page 195: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Writing constructors

Like any other function but with no return type,

car::car(int sx, int sy){

pos.x = sx;pos.y = sy;heading = north;

}

car::car();{

pos.x = 0;pos.y = 0;heading = north;

}

Page 196: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using constructors

car c1 has initial position 5,5 Car c2 calls "default constructor“

(the one with no parameters)so has initial position 0,0

car c1(5,5);car c2;

Page 197: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A world for cars

Can manipulate the public functions of car from outside the class

What other objects are there? The city is also an object The menu doesn't exist in the real

world but does exist in our model so it can also be an object

One menu per car? city? world?

Page 198: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Class data

Data which belongs to all members of the class, not per object, is declared as static The largest possible integer

Sometimes used for keeping track of the number of objects of a class

class car{public:

static int num_cars;car() ~car()

// ...};

Page 199: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Destructors Like a constructor but called when an

object is destroyed Given the class name with a ~ prefix Called automatically, cannot take or return

parameters

car::~car(){

num_cars--;}

Page 200: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Object Orientated Programming

Build models of real objects and let them communicate with each other

Much simpler to design and implement lots of small objects than to design and implement one big program

Can share the work easier Can reuse objects in other programs The silver bullet?

Page 201: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Modelling example

To simulate driving a car around a city we need, City object

• Car object Menu object

• Menu_item objects

city

car

menu

menu_item

menu_item

Page 202: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Classes

All objects belong to a particular classclass Using objects is easy Designing and writing each class is hard Choosing which classes is even harder How many objects of a class varies

one object of our class (city, mouse, cursor), a few objects (car, menu_item), lots of objects (windows, icons)

Page 203: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Modelling the solution

Often we need objects in our solution than are not a visible part of the world menu file linked list

Classes for these objects are often in the standard libraries

Page 204: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A class is a category of objects

Every object belongs to a class A class is the equivalent of a built-in

datatype (int, float) An object is the equivalent of a

variable of a data type (i1, age) We must first write the class then we

can define and use objects from that class

Page 205: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Classes Objects

car my_car city chengdu menu menu1 string s1 ifstream in istream cin

Page 206: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Declaring a class

class keyword identifier

"forward declaration" Similar to declaring a function before

you use it

class car;

Page 207: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Defining a class

class, identifier, body, semicolon The body:

Member function declarations Member object declarations Access modifiers

class car {public:

void drive_forward();std::string color;

// ...};

Page 208: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Access Modifiers

Objects have function and data members Some are members are part of it's publicly

accessible interface for other objects to make use of

Others are private and for it's own use only Use public: and private: access

modifiers to identify public and private members

Normally most or all data members will be private

Page 209: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Access modifiers

class car{public:

car();void drive_forward();void turn_left();void turn_right();int get_x();int get_y();char get_symbol();

private:struct{int x; int y;} pos;enum{north, south, east, west} heading;

};

Page 210: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Defining a class' functions

Need to specify that the function is from the car class

Use the scope operator, :: Otherwise it is just like a normal

function definitionvoid car::drive_forward(){

if(heading==east) pos.x++;// ...

}

Page 211: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Scope Operator

class car {void print();

};

class city {void print();

};

void print() {cout << "test" << endl;

}

void car::print() {cout << "test car" << endl;

}

void city::print() {cout << "test city" << endl;

}

Page 212: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Class data

Normally member functions of a class and data will logically belong with each object of a class (instance members)student s1.mark = 56;

my_car.color = red;

my_car.print();

Can also have members that are shared between all objects of a class (class wide)car::print_number();

student::passmark = 45;

Often used to keep count of the number of objects of a class or of minimum and maximum values

Page 213: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Class data

Declared using the static keyword Must be initialised outside the class

class student{public:

student(int i);int mark;static int pass_mark;string passed();

};

student::pass_mark = 50;

Page 214: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Constructors Constructing a new object from a class will call

a special function to initialise it. Must have,

the same name as the class no return type public access

class car {public:

car(int x=0, int y=0);static int num_cars;

...

A constructor function is the place to initialise all data members

Page 215: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Constructorscar::car(int sx, int sy){

pos.x = sx;pos.y = sy;heading = north;num_cars++;

}

Page 216: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Examples and a warning

constructs a new car, c1 with initial position set to 5,5

car c1(5,5);

car c2;

car c3();

int c3();

constructs a new car, c2 with initial position set to 0,0

defines a new function, c3 accepting no parameters and returning a car object!

Page 217: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Destructors

Like a constructor but called when an object is destroyed

Given the class name with a ~ prefix Called automatically, cannot take or

return parameterscar::~car(){

num_cars--;}

Page 218: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Ways to make new objects

Declaring them as a new local or global object,

car c1(5,5); constructor is called

Declaring them as a copy of another object,

car c2 = c1; copy constructor is called

Dynamically,car* c3 = new car;

constructor is called

Page 219: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Copying objects

Car c2 will also have position 5,5 and face North.

A copy constructor copies the object for us

car c1(5,5);car c2 = c1;

Page 220: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Copy constructors

The normal constructor never gets called when making a copy

We usually do not need to write our own copy constructor

A default exists which copies everything for you

Pointers included Copy constructor only gets called if a new

object is constructed, not every time an object is copied to another(copy assignment operator – another day)

Page 221: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Copy constructor

A function which Has no return type The same name as the class Has a single parameter, a constant

reference to an object of the classclass car {public: car(int x=0, int y=0); // constructor car(const car &original); // copy constructor...

Page 222: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A constant reference?

If a parameter to a function is declared as const then it cannot be changed in the function

A reference parameter is created by prefixing an ampersand ('&') to the name of the variable

Together they can speed up function calls

Page 223: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

References

Not specifically an object orientated technique but new to C++

A reference is an alias (nickname) for an object or a datatype.

car c1;car &c2 = c1;c2.color = "red";cout << c1.color; // "red"

You must set the reference to something and cannot change it later.

Not a pointer, just a second name for the object

Page 224: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Why?

We can pass objects "by reference" as parameters to function calls

void swap(int &left, int &right){

int temp = left;left = right;right = temp;

}

Do not copy the object, just a reference so can now modify values

Faster since there is less to copy

Page 225: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

OOP so far…

OOP / modelling C++ classes and objects Member operators ('.' '->') Access modifiers Constructors Copy Constructors Destructors

Enumerations References

Page 226: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Array problems

The following code doesn't work,

int size;cout << "Enter array size: ";cin >> size;int marks[size];

Memory is allocated for objects when the program is compiled

Array sizes must be known in advance

size must be a const int

Page 227: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Dynamic memory

Can create / destroy objects when the program is running using the new and delete operators

new gives the address of the newly created object

Access the object using pointers

car* pc1;pc1 = new car;pc1->color=red;pc1->driveforward();//...delete pc1;

Page 228: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Dynamic Arrays

Can create new arrays of objects Get given pointer to first element

int size;cout << "Enter array size: ";cin >> size;int* marks;marks = new int[size];// ...delete [] marks

Just have pointer to first element Use delete [] to free entire array Still cannot resize the array

Page 229: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

List object

Node object

Better than arrays

Lots of other sorts of data structure eg, Linked List

int data

node*nextnode*first

Node object

int data

node*next null

Page 230: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Algorithms & Data Structures

Examples Arrays Strings Lists Vectors Sets, Maps, Trees

This sort of data structure is called a "container" in C++

Many exist in the standard library

Page 231: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Other lists

Already have a list of integers What about a list of strings?

Just need to change all 'int' to 'string'in node class

No other changes needed What about a list of floats?

Just need to change all 'int' to 'float' What about a list of cars? Of busses?

Page 232: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Templates

Could have a list of void* void* can point to anything Can have a mixed list Have to cast from void* EVERY time

Templates are a different solution Make the type of the list a parameter to

the class

Page 233: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using templates

Consider the following function to find the address of an integer,

int* find(int item, int* start, int* sentinel){

int* i;for(i=start;i<sentinel;i++){

if (*i==item) return i;}return 0;

}

Page 234: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Using templates

Compiler can automatically generate the code for any class or datatype,

template<typename T>T* find(T item, T* start, T* sentinel){

T* i;for(i=start;i<sentinel;i++){

if (*i==item) return i;}return 0;

}

Page 235: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Back to containers…

There is a large selection of container classes in the C++ standard template library

vector map list Many more…

Page 236: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Vectors

An automatically sizing array A template class,

#include <vector>std::vector<int> name;

Can initialise to an array,int a1[] = {1,2,3,4,5};vector<int> v2(a1, a1+5);

Lots of member functions,.size() .push_back(i).front()

Page 237: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Maps

An sorted automatically growing array with anything as it's index and of any size,

Both key and value are templated,#include <map>

std::map<string, int> map1;

Lots of member functions,.find() .insert() .end()

Page 238: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Lists

Similar use as a vector Implemented as a double linked list Cannot index (no random access) Faster to insert new elements

Node object

T data

node*next

node*prev

Node object

T data

node*next

node*prev

Node object

T data

node*next

node*prev

List object

node*first

node*last

Page 239: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Iterators

An object that behaves like a pointer for accessing members of the container in turn,

for(it=start;it<=sentinel;it++)

cout << *it;

'it', 'start' and 'sentinel' are all iterators Will work the same way on ANY container

Page 240: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Getting iterators

For a container object c1,c1.begin();

c1.end(); Will return iterators pointing to the

first and sentinel elements Need to store it so can do it++ etc Need to declare it What class will it be?

Page 241: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Class for an iterator

For a container class,vector<string>

Class of iterator is available as static member of the container class,vector<string>::iterator

So can define an object of this type,vector<string>::iterator it;

Page 242: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A note on files

We usually use two files per class classname.h – declares the class classname.cpp – implements the class

Other classes (and global functions) which want to use a class just #include the header (.h) file

main function is not part of any class Usually put this in it's own file along with any

other global functions This makes programs compile faster Sometimes break the rules (esp. testing)

Page 243: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

To confuse you!

As well as source files (.cpp and .h) A build system to manage them

Visual C++ One Workspace

One or more Projects• One or more Source files

Page 244: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Inheritance

car class 小汽车 bus class 公共汽车 lorry class 载货汽车 All are a kind of vehicle (汽 )车

Can have a vehicle class and inherit other classes from it

Page 245: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Inheritance

All the members of the base class (vehicle) will apply to the derived classes (car, bus, lorry)

Our derived classes can either use the members of the base class directly or can override them

Can also add new members to derived classes

Page 246: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Public Inheritance

The most common form of inheritance is public inheritance,

Non-private members of the base class can be used in the derived classes

Need new constructors and destructors

class car : public vehicle{

car();~car();

}

Page 247: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Private Inheritance

With private inheritance no members of the base class are available and must be re-implemented

class car : private vehicle{

car();~car();void driveforward();void turnleft();// ...

}

Base class specifies the interface

Page 248: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Protected Modifier

Class members designated protected are available to derived classes (but not other classes)

class vehicle {public:

vehicle();bool drive_forward();bool change_lane_down();bool change_lane_up();int get_lane();int get_distance();

protected:int lane;int distance;

};

Page 249: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Plug compatibility

Cars, busses and lorries have a common interface

We should be able to have a mixed array (list, vector, …) of any type of vehicle

(BIG) Problem: Member functions are the same for each

object of a class Compiler saves space by having one copy Now we have an array of vehicles each with

different member functions

Page 250: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Virtual functions

In our array of vehicles we want to callcar::move_forward()

or bus::move_forward() but not vehicle::move_forward()

Functions are usually mapped to the objects at compile time

We can declare the functions in the base class "virtual" then they will map to the derived functions at run time

Page 251: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Virtual Functions Functions in the base class which are to be

over-ridden (for objects which might be used together) should be declared as virtual

class vehicle {public:

vehicle();virtual bool drive_forward();bool change_lane_down();bool change_lane_up();int get_lane();int get_distance();

protected:int lane;int distance;

};

Page 252: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Error Handling Again

Said we had three ways of dealing with errors in functions Return a special value (eg –1) Return true or false to indicate success

and use a pointer to return the data Throw an exception

What is exception handling?

Page 253: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Throwing Exceptions

throw is a special keyword to abort function callsif(n>=size) throw("too large");

Can throw any object Often throw a string which describes

the error or an integer with an error code

Can have a class specifically for exceptions and throw objects of that class

Page 254: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Exception handling

try a block of code and then catch anything thrown based on the class of the object thrown

try{

function();}catch (string s){

cout << "Error: " << s}

Destructors are called automatically Good idea but still not common practice

Page 255: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Overloading operators

We can do,cout << int1;

Why not,cout << car1;

Or for objects of a matrix class,matrix3 = matrix1 * matrix2;

Operators are a special sort of function

Can overload operators the same as we can functions

Page 256: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

A simple matrix class

Some constructors A destructor A function to return the transpose of

the matrix,

1211109

8765

4321

m

1284

1173

1062

951

Tm

A function to print the matrix Some overloaded operators

Page 257: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

operator==

Just need to compare the data in the two objects

Also have operator!=, operator>, operator< etc, etc

bool matrix::operator==(const matrix& lhs){

for(int i=0; i<size; i++)if(*(data+i) != *(lhs.data+i))

return false;return true;

}

Page 258: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Copy assignment

A copy constructor is called when we construct one object from another.

What about when we assign one object to another?

car c1(5,5);car c2(6,6);c1 = c2;

int i1(5);int i2(6);i1 = i2;

Are not creating a new object Just using an operator, '='

Page 259: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

operator=

The assignment operator is the equals sign ('=')

Can overload this operator the same as everything else

The default function does a member-wise copy

Copies pointers, not the memory pointed to

Page 260: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

operator=

Unlike our copy constructor the object already exists

Just need to copy the data from one object to the other

matrix& matrix::operator=(const matrix& original){

for(int i=0; i<size; i++)*(data+i) = *(original.data+i);

return *this;}

Page 261: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

operator<<

The << operator takes an object of the ostream class and an object of another class and returns the ostream classcout << "Hello " << "world"

(cout << "Hello ") << "world"

ostream& operator<<(ostream& out, string& s)

Operates on ostream objects not strings Cannot be a member of the string class

We use this function to call a member of the matrix class

Page 262: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

The Way Ahead

Topic summary Learning more Examples revisited Case Studies Exam preparation

Page 263: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Why C++ C++ is a 'better' C Is Object Orientated Can use streams Is strongly 'typed' Big, Fast, Powerful programs

English for Computer Programmers Using Visual C++

Page 264: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Branching If If else Statement Blocks Nested If Goto Switch

Page 265: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Looping While Do Break Continue For

Page 266: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Arrays Declaring Accessing For loop idiom C style strings

Array Problems Off by one Fixed Size Buffer Overuns

Page 267: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Functions Return a value of a known type Takes 0 or more parameters Data passed by value Data is local to function Static data maintained between calls Global data shared between all

functions (object data, class data, file data)

Page 268: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Functions Function which calls itself is recursive Can give default values Can be overloaded Are independent parts of program

• Helps us organise code• Should think about errors at the function

level

Page 269: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Memory and Pointers Data, Objects, Functions stored in mem Can get address with & operator Can store in a pointer variable

• Specify type followed by an * Dereference with * operator Can find size of object or type with sizeof

Page 270: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Memory and Pointers Null pointers Void datatype Pointers to pointers Pointers to functions Arrays and functions without [] or () are

treated as const pointers Can pass memory address to function In C++ also have references

Page 271: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Structured Programming In C use struct to structure data

• '.' member operator• '->' member from pointer operator

C++ is OO; group functions and data• A new way of thinking about programming• A BETTER way of thinking about progra……• Usually use the class keyword

Page 272: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Classes Declare member functions and data

'inside' the class keyword Define static data and functions outside

with the :: operator Define object data in the constructor

Page 273: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Access Modifiers public, private, protected Aim to hide data – class is an independent

entity Constructor

Initialise object data Allocate Resources

Copy Constructor Default copies everything – including pointers

Destructor Free resources

Page 274: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Dynamic memory new, delete arrays

Data structures Tour of the STL

Templates Compiler generates different versions of

classes and functions

Page 275: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Summary

Iterators Pointer like object for traversing data structures Many standard algorithms use iterators Work same way on all data structures

Inheritance Powerful modelling technique Base and Derived Classes Public and Private inheritance Polymorphism

Exception handling Operator Overloading

Page 276: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

More?

C++ is big and powerful Standard libraries are huge Windows + Posix libraries are bigger Know MOST of C++ language; can

use all the libraries Books, websites, examples, jobs

Page 277: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Idioms in C++

KISS Traversing an array with a for loop Use of sentinel values Multiple files Double include macro guards

Page 278: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Data types

C++ is very 'type safe' Can define our own data types Can use those from the library Many are built in

char, short, int, long, enum double, float

Modifiers unsigned, const

Can force conversion between types

Page 279: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

The pre-processor

Building is several steps Compiling

Pre-processing Linking

Pre-processor has it's own language Instructions start with the # symbol

Page 280: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Scope

Can only access data if program can currently "see" it

Declared first Local to function Local to object Local to class Local to file / global In correct namespace Use :: operator when have a choice

Page 281: C++ Computer Programming Matthew Ryan& 母培新 C++ Computer Programming Matthew Ryan& 王茂芝

Important examples

Two case studies, shapes cars

Also some important examples Guess my age For loops and arrays Number sequences Functions Pointer Arithmetic