Upload
stanley-mosley
View
250
Download
0
Embed Size (px)
Citation preview
C++ Computer Programming
Matthew Ryan & 母培新
An Introduction
Why English? About the course About Matt
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
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
A different style of teaching
China 1 course, 1 book
England No book / lots of books
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
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!
Course Content
Computer architecture English for computer programmers Procedural programming concepts Object Orientated Methodology The C++ standard template library Thinking skills
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!
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
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
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
New (English) words
Computer Program - source code (programmer sees)
New (English) words
Computer Program - executable (user sees)
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
Computer Hardware
A programming course Just a quick tour Will be useful later
Memory Information Architecture
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)
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
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
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
Lecture 2
Last week Introduction to the course and Matt Binary and Hexadecimal Systems Computer Memory
Today Representing information Running programs Writing programs
Representing information
Can use our groups of bits to store information Text Decimal numbers Pictures Sounds Computer programs
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
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
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
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
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
Binary coded decimal
0000 0 0001 1 0010 2 0011 3 … … 1000 8 1001 90001 0000 100001 0001 11 … …0010 0000 20
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
Converting Binary to Decimal
Very simple system
0
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
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
Machine Architecture
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
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
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
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
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
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
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
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!
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
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
Lecture 3
Today IDEs Visual C++ Writing our own programs Words for parts of programs
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
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
Window Names
Output Window
Workspace Window
menu
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;}
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
$
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;}
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;}}
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));;
}}
...
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;}}
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));
}}
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;}
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
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;}
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;}
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;}
English Summary
Functions Statements Statement Block Keywords Data Types Identifiers
Variable names Function names
Operators
New C++ features
Object Orientated Datatypes Classes Variables Objects
A library of standard classes string, cout, vector
Lots more…
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
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;
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); }}
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
$
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::
cout.cpp#include <string>#include <iostream>
int main(void){ std::string s1 = "Hello World\n"; std::cout << s1;std::cout << "Hello again" << std::endl;
}
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
$
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::
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';
}
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$
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 ( + - ++ << )
C++ Summary
Object Orientated Programming C++ Programming is easier than C string class cin and cout objects endl object
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;}
Exercise 1.2a
Break the program
...int main() { string user_name; ...
...int main() { //string user_name; ...
After:
Before:
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
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
Declaration statements
int age;string user_name;float height, weight;
int age=26;string user_name="Matt";float height=1.75, weight=122.5;
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);
Exercise 1.2
Break the program!
#include <iostream>#include <string>using namespace std;...
//#include <iostream>#include <string>using namespace std;...
After:
Before:
#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
Exercise 1.3
Break the program!
...int main() { string user_name;...
...int my_main() { string user_name;...
After:
Before:
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
Common errors
Undeclared objects Forget to declare Spelling errors Namespace errors (std::)
Forgetting the semicolon (;) Using Chinese punctuation
{…} (…) […] <…> "…" '…' ? ! : ; Project errors
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
Normal flow
Statement 1;
Statement 2;
Statement 3;
Statement 4;
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
if flow
Condititional Statementif(…)true
false
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
if else flow
Condititional Statementif(…)
else Statement
truefalse
Statement Blocks
Can also use statement blocks ({…})
if (height < 1.4){ price=30; type="child";}else{ price=50; type="adult";}
Nested if statements
if (height<0.6) {price=0;
}else { if (height<1.4) price=30; else price=50;}
Nested if flow
Condititional Statement 2else if
else if Condititional Statement 3
Else Statement
Condititional Statement 1if true
true
true
false
false
false
goto
"Go to" part of a program
Not recommended!
if (height < 0) goto error;.........error:cout << "Error !"
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
Switch statementswitch(price) {case 0:
type="baby";break;
case 30:type="child";break;
case 50:type="adult";break;
default:type="unknown";
}
switch flow
Condititional Statement 2case 2
case 3 Condititional Statement 3
Condititional Statement 1case 1
switch
Branching Flow Control
if if else nested if (if – else if – else if – else) (goto) switch
Conditional Statements
if if else nested if (if – else if – else if – else) statement blocks ({…}) (goto) switch (case, default, break)
Normal flow
Statement 1;
Statement 2;
Statement 3;
Statement 4;
if
if (a) b; If a is true then do b
...if (height<1.4) price*=0.7;...
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;
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
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
while loop
while (expression) something
while (guess!=age){
cout << "Guess my age: ";cin >> guess;
}
while flow
Condititional Statementswhile(…)true
false
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);
do flow
condititional statements
while(…)true
false
do
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;
}
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;......
}
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.
for loop
Most used – most complicated Normally used for counting Four parts
Initialise expression Test expression Body Increment expression
for loop
body statements
continuationtest
initialisation
increment
true
false
for loop
int count;
for (count=1; count<=10; count++)
{
cout << count
<< " squared is "
<< (count*count)
<< '\n';
}
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
Flow control summary
branching if if-else nested if (goto) switch
looping while do-while for
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
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
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?
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
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
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++
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
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
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
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…
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
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"};
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}
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;}
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
for loop
print e and element at e
is e<11
e=0
e++
yes
no
There are 11 elements, 0 to 10
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
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';}
}
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
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!
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
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)
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';
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);
}
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);
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
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 { ... }
Function Flow
Statement 1;
Statement 2;
function(…)
Statement 4;
Statement 1;
Statement 2;
Statement 3;
Statement 4;
main() function()
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
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
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; }
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(){...}
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
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}
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++;...
}
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));
}
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");
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
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
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.
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
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
struct
struct student{int id;string name;int mark;
};
Groups data types together Yet another use of brackets! Don't forget the last semicolon
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;
Structured programming
Computer programs are operations on information
Operations are functions Information is structured data Our programs model the way the
computer works
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
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
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
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
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
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
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
Pointers Summary
'size of' operator sizeof(i) 'address of' operator &i pointer datatypes int* p1 value of (dereference) *p1 null pointers p1=0
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;
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
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;
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
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;
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
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
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
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?
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
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);
}
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
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;
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;
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
A class for cars
Operations: Drive forward Turn left Turn right
Information: Position Direction facing
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;
};
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;
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
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;
};
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--;
// ...
}
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;
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
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();// ...
};
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;
}
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;
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?
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()
// ...};
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--;}
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?
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
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)
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
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
Classes Objects
car my_car city chengdu menu menu1 string s1 ifstream in istream cin
Declaring a class
class keyword identifier
"forward declaration" Similar to declaring a function before
you use it
class car;
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;
// ...};
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
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;
};
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++;// ...
}
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;
}
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
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;
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
Constructorscar::car(int sx, int sy){
pos.x = sx;pos.y = sy;heading = north;num_cars++;
}
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!
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--;}
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
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;
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)
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...
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
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
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
OOP so far…
OOP / modelling C++ classes and objects Member operators ('.' '->') Access modifiers Constructors Copy Constructors Destructors
Enumerations References
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
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;
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
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
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
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?
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
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;
}
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;
}
Back to containers…
There is a large selection of container classes in the C++ standard template library
vector map list Many more…
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()
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()
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
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
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?
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;
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)
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
Inheritance
car class 小汽车 bus class 公共汽车 lorry class 载货汽车 All are a kind of vehicle (汽 )车
Can have a vehicle class and inherit other classes from it
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
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();
}
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
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;
};
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
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
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;
};
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?
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
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
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
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
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;
}
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, '='
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
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;}
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
The Way Ahead
Topic summary Learning more Examples revisited Case Studies Exam preparation
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++
Summary
Branching If If else Statement Blocks Nested If Goto Switch
Summary
Looping While Do Break Continue For
Summary
Arrays Declaring Accessing For loop idiom C style strings
Array Problems Off by one Fixed Size Buffer Overuns
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)
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
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
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
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
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
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
Summary
Dynamic memory new, delete arrays
Data structures Tour of the STL
Templates Compiler generates different versions of
classes and functions
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
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
Idioms in C++
KISS Traversing an array with a for loop Use of sentinel values Multiple files Double include macro guards
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
The pre-processor
Building is several steps Compiling
Pre-processing Linking
Pre-processor has it's own language Instructions start with the # symbol
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
Important examples
Two case studies, shapes cars
Also some important examples Guess my age For loops and arrays Number sequences Functions Pointer Arithmetic