Upload
lynguyet
View
246
Download
1
Embed Size (px)
Introduction to Modern Scientific Programming
Introduction to Modern Scientific Programming
Dr. Markus Kirkilionis, Martin Eigel, Dr. Luca Sbano
Mathematics Department,University of Warwick
10/04
C++ Part C++ (4)
1
Introduction to Modern Scientific Programming
Part I
Introduction to the MatLab environment
2
Introduction to Modern Scientific Programming
Overview Part I
Basic UNIX shellUseful Commands
The MatLab EnvironmentCalculator FunctionsFunctions and plotting
Programming with MatLabProgramming LanguageAdvanced Graphics
MatLab
3
Introduction to Modern Scientific Programming
UNIX login
I Each user has his own home directory (path:"/home/username"). You start in that directory after loggingin.
I Paths can be absolute ("/usr/bin/kate") or relative("mydir/testprog") to the current directory.
I Your home directory also has the label "~" (e.g."~/moac/ex1").
I Pressing TAB once/twice triggers auto-completion on thecommand line.
4
Introduction to Modern Scientific Programming
Shell commands
command description
pwd print working directorycd <dir> change directory to dir
(".." is the parent directory,just ”cd” changes home directory)
mkdir <name> make directoryrmdir <name> remove directorycp <file1 ...> <dest> copy files/directories to destinationmv <file1 ...> <dest> move files/directories to destinatonrm <opt> <file1 ...> remove files; option ”-rf” (recursive,
force) removes entire directory treesls <opt> list directory contents; use with ”-l”
for extended infos
5
Introduction to Modern Scientific Programming
Shell commands (cont.)
command description
more <textfile> view textfile pagewiseless <textfile> scroll through textfile; exit with ”q”
man <cmd> get manual pages for command; usecursor keys for scrolling, exit with ”q”
apropos <keyw> list all commands including keyword
tar xvzf <arch.tar.gz> extract archive to current directory(flags: extract, verbose, zip-archive(”.gz”), filename)
ps process status shows list of processeskill <pid> kills process (in case it locked/crashed);
use option ”-9” for an enforced kill
6
Introduction to Modern Scientific Programming
UNIX software
Useful programs
kate easy to use text editorwith syntax highlighting
emacs, vim advanced editors
mozilla Web Browserskonqueror
opera
xmms Multimedia programsmplayerooffice OpenOffice (similar to MS Office)
7
Introduction to Modern Scientific Programming
UNIX software (cont.)
Useful programs
matlab MatLab programoctave free MatLab clonesscilab
KDevelop Integrated Development EnvironmentsAnjuta
gimp 2 2D graphics program (like Photoshop)sodipodi 2D vector graphics programblender 3D modeller and renderer
8
Introduction to Modern Scientific Programming
Before we start
Preliminaries
>> MatLab prompt, waiting for user input% starting a comment line; if a command line is ended with ”;”,
MatLab will not print the result of the command= assignment operator
Help/Info
help <cmd> command name is optionalwhos show defined variablesans last MatLab answermore on/off page-wise output on/offclear * clear all defined variables
CTRL + C cancel current calculation
9
Introduction to Modern Scientific Programming
MatLab as a calculator
Predefined functions (like sin, cos, tan, log, sqrt) can befound within the MatLab help system (help elfun).
1 >> 2∗6.4+12ˆ52 ans = 2.4884 e+053
4 >> s i n (2∗ p i )+1.4 i+sqr t (3 )5 ans = 1.7321 + 1.4000 i
10
Introduction to Modern Scientific Programming
Vectors and Matrices
Assigning values to vectors and matrices:
1 >> n = 7 % s c a l a r
2 >> A = [ 1 2 3 4 5 ] % 1 x5 mat r i x
3 >> B = 1 : 5 % same as above
4 >> C = 1 : 2 : 1 0 % 1 x5 mat r i x w i th s t e p s i z e 2
5 >> D = n : −0 . 3 : 1 % produce s a 1 x21 mat r i x
6 >> E = [ 1 ; 2 ] % 2 x1 mat r i x
7 >> F = [ 1 2 ; 3 4 ] % 2 x2 mat r i x
8 >> s = ’ s t r i n g t e s t ’ % s t r i n g as s i gnment
9 >> A ’ % con juga t e t r a n s p o s e mat r i x
11
Introduction to Modern Scientific Programming
Matrix access1 >> A = rand ( 3 , 3 )2 A =3 0 .84434 0 .28686 0.140044 0 .26009 0 .57137 0.895385 0 .96570 0 .73364 0.467776 >> A(1 , 2 )7 ans = 0.286868 >> A(2 , 2 : 3 )9 ans =
10 0 .57137 0.8953811 >> A( 2 , : )12 ans =13 0 .26009 0 .57137 0.8953814 >> s = ’ t e s t ’ ;15 >> s (2 )16 ans = e
12
Introduction to Modern Scientific Programming
Arithmetic Operators
X + Y Addition between equally size matrices or with scalar YX - Y SubtractionX * Y Matrix multiplicationX .* Y Element by element multiplicationX / Y Right division (eq: ((Y ′)−1 ∗ X ′)′)X ./ Y Element by element right divisionX \ Y Left division (eq: X−1 ∗ Y )X .\ Y Element by element left division
13
Introduction to Modern Scientific Programming
Arithmetic Operators (cont.)
X ^ Y Power operatorX .^ Y Element by element power operator-X NegationX’ Complex conjugate transposeX.’ Transpose
See also help matfun for further matrix functions.Comparison operators are the usual suspects:X < Y, X <= Y, X == Y, X<>Yand so on.
14
Introduction to Modern Scientific Programming
Creating matrices
zeros(m,n) zero m × n matrixones(m,n) m × n matrix of oneseye(n) n × n identity matrixdiag(v) n × n matrix with v (an n-vector) on its diagonal
1 >> A = rand ( 2 , 3 ) % random 2 x3 mat r i x
2 A =3 0 .466753 0 .415569 0.3938084 0 .749506 0 .020459 0.5287075
6 >> b = rand ( 1 , 2 ) % random ve c t o r o f s i z e 2
7 b =8 0 .62804 0.36830
15
Introduction to Modern Scientific Programming
Basic function plotting
1 >> x = −5:5;2 >> y = x . ˆ 3 ;3 >> p l o t ( x , y ) % p l o t as connected graph
4 >> p l o t ( x , y , ’ o ’ ) % p l o t on l y p o i n t s
-150
-100
-50
0
50
100
150
-6 -4 -2 0 2 4 6
line 1
Other useful functions:hold on/off, title(string)x/ylabel(string)axis(range)text(x,y,string)legend(name1, name2,...)
16
Introduction to Modern Scientific Programming
Basic function plotting (cont.)
1 % 100 p o i n t s i n [ 0 , 1 ]
2 >> x1 = l i n s p a c e ( 0 , 1 , 1 0 0 ) ;3 % 100 p o i n t s i n [0 ,10ˆ −1]
4 >> x2 = l o g s p a c e (0 ,−1 ,100) ;5 >> p l o t ( x1 , x1 . ˆ 3 . ∗ s i n ( x1 ) , x2 , tan ( x2 ) )6 >> x l a b e l ( ’ x ’ ) , y l a b e l ( ’ f ( x ) ’ )7 % se t t i t l e , d i s p l a y g r i d , a l l ow a d d i t i o n a l p l o t s i n graph
8 >> t i t l e ( ’ s i n ( ) and tan ( ) ’ )9 >> g r i d
10 >> ho ld on11 >> p l o t ( x2 , z e r o s ( s i z e ( x2 ) ) , ’+ ’ )12 % se t v i ewpo r t to 1 <= x <= 5, −10 <= y <= 10
13 >> a x i s ( [ 1 5 −10 10 ] )
17
Introduction to Modern Scientific Programming
-1
-0.5
0
0.5
1
1.5
2
0 0.2 0.4 0.6 0.8 1
f(x)
x
line 1line 2line 3
18
Introduction to Modern Scientific Programming
Other basic commands
max(x) return largest entry of xmin(x) return smallest entry of xabs(x) return absolute valuessize(A) return 1× k vector of As dimensionslength(A) length of array is max(size(A))save <fname> save variables to fileload <fname> load variables from filequit exits MatLab
19
Introduction to Modern Scientific Programming
Script files
I Matlab files have suffix ”.m”.
I They include scripts (list of commands like in a user session)or a single function of the same name as the file.
I Script/Function files have to be in working directory (pwd) orin one of the directories included in the search path.
I Scripts/Functions are executed by typing their filename(without suffix).
I Matlabs own text editor can be started with the commandeditor.
20
Introduction to Modern Scientific Programming
Control structures: Conditions
The if <exp> <...> elseif <exp> <...> else <...>construct is used to execute code depending on given conditions.
1 >> i f b > 02 c = a/b ;3 e l s e i f b < 04 c = −a/b ;5 e l s e6 c = 0 ;7 end
21
Introduction to Modern Scientific Programming
Control structures: Loops
for loops typically involve a running variable like i=1:n,
1 >> n = 13 ;2 >> f a c = 1 ;3 >> f o r i =2:n4 f a c = i ∗ f a c ;5 end6 >> fac , c l e a r f a c
while loops are executed while a certain condition is fulfilled.
1 >> n = 0 ;2 >> wh i l e n+1 <= x3 n = n+1;4 end5 >> n
The break command can be used to terminate loops.
22
Introduction to Modern Scientific Programming
Iterations in MatLab
Algorithm to compute the square root of 2, implemented inMatLab:
1 >> n = 1 ;2 >> x (1)=1;3 >> wh i l e n+1 <= 104 x ( n+1) =x (n)+(2−x ( n )ˆ2)/(2∗ x ( n ) ) ;5 n=n+1;6 end7 >> x
23
Introduction to Modern Scientific Programming
Iterations in Octave
Algorithm to compute the square root of 2, implemented inOctave:
1 octave > n = 1 ;2 octave > x (1)=1;3 octave > wh i l e ( n+1 <= 10)4 > x ( n+1)=x (n)+(2−x ( n )ˆ2)/(2∗ x ( n ) ) ;5 > n++6 > endwh i l e7 octave > x
24
Introduction to Modern Scientific Programming
Differential Equations in MatLab
Euler Algorithm to numerically integrate the ODE:
dx(t)
dt= x(t)(1− x(t)), x(0) = a
implemented in MatLab:
1 >> n = 1 ;2 >>h=0.01;3 >> x (1)=a ;4 >> wh i l e n+1 <= 1005 x ( n+1) =x (n)+h∗( x ( n)∗(1−x ( n ) ) ) ;6 n=n+1;7 end8 >> p l o t ( x )
25
Introduction to Modern Scientific Programming
Differential Equations in Octave
Euler Algorithm to numerically integrate the ODE:
dx(t)
dt= x(t)(1− x(t)), x(0) = a
implemented in Octave:
1 octave > n = 1 ;2 octave>h=0.01;3 octave > x (1)=a ;4 octave > wh i l e ( n+1 <= 10)5 > x ( n+1)=x (n)+h∗( x ( n)∗(1−x ( n ) ) ) ;6 > n++7 > endwh i l e8 octave > gp l o t ( x )
26
Introduction to Modern Scientific Programming
Functions
By writing function files (”.m” suffix and function keyword) onecan define custom functions that behave just like the built in ones.
1 f u n c t i o n d = d i s t ( a , b )2 % DIST . C a l c u l a t e d i s t a n c e .
3 % DIST(a , b ) r e t u r n s d i s t a n c e between a and b .
4
5 ba = b − a ; % ba and dd a r e l o c a l v a r i a b l e s !
6 dd = ba ∗ ba ’ ;7 d = s q r t ( dd ) ;8 % end o f f u n c t i o n d i s t
By providing an appropriate comment directly after the functiondefinition, help square will show exactly that.Source of several routines can be examined by using type, e.g.type rank.
27
Introduction to Modern Scientific Programming
Functions (cont.)
nargin equals the number of arguments given to the function.error can be use to print an error message to the user.
1 f u n c t i o n d = d i s t ( a , b )2 % DIST . C a l c u l a t e d i s t a n c e .
3 % DIST(A,B) r e t u r n s d i s t a n c e between A and B.
4 i f ( na r g i n ˜= 2)5 e r r o r ( ’ Not enough i npu t arguments ’ ) ;6 end7 i f ( s i z e ( a , 1 ) ˜= s i z e (b , 1 ) )8 e r r o r ( ’A and B not o f same d im e n s i o n a l i t y ’ ) ;9 end
10
11 ba = b − a ;12 d = ba ∗ ba ’ ;13 d = s q r t ( dd ) ;14 % end o f f u n c t i o n d i s t
28
Introduction to Modern Scientific Programming
Functions (cont.)
Multiple return values are simply defined as a row vector.
1 f u n c t i o n [ vo l , d i a ] = c u b e p r o p e r t i e s (q , d )2 % CUBEPROPERTIES . Volume and l e n g t h o f d i a g on a l o f cube .
3 % CUBEPROPERTIES(Q,D) r e t u r n s volume VOL and l e n g t h o f
4 % d i a g ona l DIAG o f a D−d imen s i o n a l cube wi th s i d e l e n g t h s Q.
5 % D i s op t i o n a l , d e f a u l t i n g to 2 .
6 i f n a r g i n < 27 d = 2 end8 v o l = qˆd ;9 d i a = q∗ s q r t ( d ) ;
10 % end o f f u n c t i o n c u b e p r o p e r t i e s
The function can be called like this:[vv,dd] = cubeproperties(1.4,3)[vv,dd] = cubeproperties(2.2) (implicitly q = 2)
29
Introduction to Modern Scientific Programming
Functions: recursion
Functions can of course call themselves. For calculating theFibonacci sequence given by
fn = fn−1 + fn−2, f0 = f1 = 1
we define function fibonacci.
1 f u n c t i o n f n = f i b o n a c c i2 n = i n p u t ( ’ Type i n f i b o n a c c i number : ’ ) ;3 i f n == 04 f n = 1 ;5 e l s e i f n == 16 f n = 1 ;7 e l s e8 f n = f i b o n a c c i ( n−1) + f i b o n a c c i ( n−2);
input requests user input, disp displays a string.
30
Introduction to Modern Scientific Programming
3D plots
meshgrid generates the product set X × Y elements of which canthen be used for evaluating functions at.
1 >> x = (0 :2∗ p i /20 :2∗ p i ) ;2 >> y = ( 0 : 1 / 4 0 : 1 ) ;3 >> [X ,Y] = meshgr id ( x , y ) ;4 >> Z = s i n (X) . ∗ exp (Y ) ;5 >> mesh (X,Y, Z ) ; % unshaded
6 >> s u r f (X,Y, Z ) ; % shaded
7 >> con tou r (X,Y, Z ) ; % contou r p l o t
With subplot(m,n,i) you can create several (i.e. m ∗ n) plots ina single window.
31
Introduction to Modern Scientific Programming
3D plots (cont.)
peak(n) generates a n × n demo data set.
1 >> s = peaks ( 5 0 ) ;2 >> mesh ( s )3 >> c on t ou r f ( s ) % f i l l e d contou r p l o t
4 >> co lormap ( hot )5 >> s had i ng i n t e r p6 >> r o t a t e 3d on
Other options:colormap ([flag | gray | hsv | jet | prism | ...])shading [interp | flat | faceted]
32
Introduction to Modern Scientific Programming
Parametric plots
Parametric plots (f (t), g(t)) are straightforward:
1 >> t = (0 :2∗ p i /100:2∗ p i ) ’ ;2 >> p l o t ( cos ( t ) , s i n ( t ) ) % pa r ame t r i c p l o t
3 >> a x i s ( ’ s qua r e ’ ) % make s c a l i n g equa l
Other useful commands (use help)loglog, semilogx, semilogyprint, printopt
Also browse the online doc!
33
Introduction to Modern Scientific Programming
Part II
Introduction to Object Oriented Programming withC++
34
Introduction to Modern Scientific Programming
Overview Part II
Execution ControlConditionals and LoopsWriting and Compiling Your Source Code
Object Oriented ProgrammingConcepts of OO
More Advanced C++
35
Introduction to Modern Scientific Programming
Introduction
Some prerequisites before we can start with Object Orientation(OO):
I Definition of variables
I Definition of functions
I Execution control statements.
I The compiler model.
We will then move on to the central idea of OO: the class.
36
Introduction to Modern Scientific Programming
IntroductionSome General Remarks
I A block/group of code (i.e. a compound statement) isdenoted by braces ”{ }”.When the term statement is used in this notes, it can be asingle statement or a compound one.
I Variables declared within "{ }"-groups are only accessiblewithin the nearest group (scope). This is called scoping.
I Variables declared outside any compound statements areglobally accessible. This should be avoided however, as itmakes code hard to understand and error prone.
I To compile (i.e. generate an executable file) and test code,you will need to define at least a main() function for yourprogram. This will be explained shortly.
37
Introduction to Modern Scientific Programming
IntroductionDeclaration and Definition
A C++ program is a collection of variables, functions, definitionsand function calls.
I A declaration introduces a new identifier to the compiler:”This function or this variable exists somewhere and here iswhat it should look like”.
I A definition means: ”Make this variable or this functionhere”.In this case the compiler actually allocates storage for thefunction or variable.
Declarations have to occur before you access the respectiveidentifiers!
38
Introduction to Modern Scientific Programming
IntroductionDeclaration & Definition of Variables
In contrast to most scripting languages C++ is strongly typed, i.e.every variable is of a fixed type.Declaring a variable: TYPE variablename;Basic types are int, unsigned int, long, unsigned long,float, double, char.
1 i n t i n t e g e r 1 = 2 ;2 i n t i n t e g e r 2 , i n t e g e r 3 ;3 i n t e g e r 2 = 5 ;4 i n t e g e r 3 = ( i n t e g e r 1 + i n t e g e r 2 ) ∗ i n t e g e r 2 ;5
6 double mydouble = 3 . 141 ;7 char mycharac te r = ’ a ’ ;
Note: Each statement has to be terminated by a ”;”.
39
Introduction to Modern Scientific Programming
IntroductionBoolean operators
A boolean variable can be either false or true:"bool my flag = true;"
logical op sample
&& AND true && false == false|| OR true || false == true! NOT !false == true
Note: For bitwise AND, OR, XOR and the complement theoperators "&, |, ^, ~" have to be used1: "5 & 4 == 4".
1valid for cardinal types char, int, long
40
Introduction to Modern Scientific Programming
IntroductionType Casting
I Sometimes it is necessary to explicitely change the type of avariable.
I This is called type casting.
I The syntax is: (NEW TYPE)variable
1 i n t i = 2 ;2 double d1 , d2 , d3 ;3 d1 = i /3 ; / / p e r f o r m s i n t e g e r d i v i s i o n
4 d2 = i / 3 . ; / / p e r f o r m s d o u b l e d i v i s i o n
5 d3 = ( double ) i /3 ; / / d i t o
Note: Casting is considered bad coding style and should beprevented whenever possible. C++ offers casting templates thatare more type safe.
41
Introduction to Modern Scientific Programming
IntroductionArrays
I An Array is a sequential list of a certain type.
I It can be defined by "TYPE arrayname[SIZE];". The size isfixed at compile time, i.e. it has to be a constant number, nota variable!
I Access an element of the array by "arrayname[POS]".
I The index starts at 0 and ends at SIZE-1.
1 char cAr r [ 4 ] = { ’ a ’ , ’ c ’ , ’ g ’ , ’ t ’ } ;2 s t d : : cout << ” Las t : ” << cAr r [ 3 ] ;3
4 i n t i A r r [ 1 0 ] ;5 f o r ( i n t i = 0 ; i < 10; ++ i )6 i A r r [ i ] = 10− i ;
Note: Arrays defined like this can not change their size dynamically.We will get to better methods when discussing STL containers!
42
Introduction to Modern Scientific Programming
IntroductionDeclaration of Methods and FunctionsDeclaring a function(we’ll come to details later!):return TYPE functionname(param TYPE varname[, ...]);
1 / / f u n c t i o n d e c l a r a t i o n
2 void p r i n tSometh i ng ( ) ;3
4 / / c o u l d u s e p r i n t S o m e t h i n g ( ) h e r e a l r e a d y ,
5 / / b u t n o t s q u a r e ( x ) !
6
7 / / f u n c t i o n d e f i n i t i o n
8 void p r i n tSometh i ng ( ){9 s t d : : cout<<” I got c a l l e d ” ;
10 }11
12 / / d e c l a r a t i o n a n d d e f i n i t i o n o f f u n c t i o n
13 unsigned i n t squa r e ( i n t number ){14 return number∗number ; }
Note: std::cout is the standard output stream printing to theconsole. For using it, the iostream classes have to be included atthe top of the file: #include <iostream>
43
Introduction to Modern Scientific Programming
Introduction Scope Example
1 i n t i 1 = 3 ; / / g l o b a l v a r i a b l e i 1
2
3 void func ( ){4 i n t i 2 = i 1 ; / / c a n s e e i 1
5 }6
7 i n t main ( ){8 i n t i 3 = i 1 ; / / c a n s e e i 1
9
10 {11 i n t i 4 ;12 }13
14 / / c a n n o t s e e i 2 , i 4 , i 5 h e r e !
15 i n t i 5 ;16 }
44
Introduction to Modern Scientific Programming
IntroductionExecution Control
Classical control structures are inherited from C:
I if-else statement
I while and do-while loops
I for loop
I switch-case selection statement.
These are similar to other imperative programming languages2.They depend on a boolean expression that can be either true orfalse.
Boolean Comparison
Use the common operators < > <= >= != and pay attention tothe equality operator ==. Don’t confuse it with the assignment =.
Moreover, nonzero values are always considered being true(i.e. 0 == false).
2Pascal, Basic, Ada, Matlab, Fortran, Java, . . .
45
Introduction to Modern Scientific Programming
IntroductionExecution Control: if-else
Two forms are possible:
1 i f ( e x p r e s s i o n )2 s ta tement3
4
5 i f ( e x p r e s s i o n )6 s ta tement7 e l s e8 s ta tement
Note: It is common to indent your code according to its logicalstructure3. This makes the code much easier to read.
3pay attention to the provided examples!
46
Introduction to Modern Scientific Programming
Introductionif-else example
I The standard function rand() returns an integer number in[0,RAND MAX ]. Requires: "include <stdlib.h>"
I std::cout and std::cin denote the console output andinput streams.
I Use operators << and >> for sending and receiving data.
1 unsigned i n t r a n d i n t = rand ( ) ;2 i f ( r a n d i n t <= 1000){3 s t d : : cout << ” r a n d i n t i s : ” << r a n d i n t ;4 } e l s e s t d : : cout << ” r a n d i n t i s l a r g e r than 1000” ;
47
Introduction to Modern Scientific Programming
IntroductionExecution Control: while
The expression can be evaluated at the beginning or at the end ofthe loop:
1 whi le ( e x p r e s s i o n )2 s ta tement3
4
5 do6 s ta tement7 whi le ( e x p r e s s i o n )
Note: You can break out of a while and for loop or jump to thenext iteration by using
break quit the loop
continue stops current iteration and goes back to beginningfor next iteration.
48
Introduction to Modern Scientific Programming
Introductionwhile example
1 unsigned i n t r a n d i n t = rand ( ) ;2 whi le ( r a n d i n t < RAND MAX/2)3 r a n d i n t = rand ( ) ;4
5
6 whi le (1){7 i f ( ( double ) rand ( )/RAND MAX > 0 .9)8 break ; / / l e a v e u n c o n d i t i o n a l l o o p
9 e l s e s t d : : cout << ” . ” ;10 }11
12
13 i n t i ;14 do { / / n u m b e r 0 w i l l e x i t l o o p
15 s t d : : c i n >> i ;16 }whi le ( i != 0 ) ;
Note: do-while is executed at least once, even if the initialcondition is false.
49
Introduction to Modern Scientific Programming
IntroductionExecution Control: for
Normally applied for ”counting” loops:
I Initialisation before the first iteration.
I Conditional testing.
I Some form of ”stepping” to alter the conditional expression.
1 f o r ( i n i t i a l i s a t i o n ; c o n d i t i o n a l ; s t e p )2 s ta tement
50
Introduction to Modern Scientific Programming
Introductionfor example
1 / / p r i n t n u m b e r s 1 . . 1 0
2 f o r ( i n t i = 0 ; i < 10; ++ i )3 s t d : : cout << ” i : ” << i << s t d : : e nd l ;4
5 / / w a i t f o r k e y ” q ”
6 f o r ( char c = ’ ’ ; c != ’ q ’ ; s t d : : c i n >> c ) ;
Note: ++ and -- denote the increment and decrement operators,i.e. ++i means i = i + 1.
51
Introduction to Modern Scientific Programming
IntroductionExecution Control: switch-caseMulti-way selection:
I Selector gives an integral value.
I This is compared to the defined values.
I If a matching value is found, the statement is executed.
I If no match is found, default is executed.
1 switch ( s e l e c t o r ){2 case i n t e g r a l −va l u e1 : s ta t ement ; break ;3 case i n t e g r a l −va l u e2 : s ta t ement ; break ;4 . . .5 de fau l t : s t a t ement ;6 }
Note: The trailing break quits the execution in the switchstatement. Otherwise execution would run though all followingstatements.
52
Introduction to Modern Scientific Programming
Introductionswitch-case example
1 char c ;2 bool end = f a l s e ;3 do{4 s t d : : c i n >> c ;5 switch ( c ){6 case ’ h ’ :7 s t d : : cout << ”Hi t h e r e ! ” ;8 break ;9 case ’Q ’ :
10 case ’ q ’ :11 end = true ;12 break ;13 de fau l t :14 s t d : : cout << ”Unknown command . ” ;15 }16 whi le ( ! end ) ;
53
Introduction to Modern Scientific Programming
IntroductionThe main function
I Function int main(int argc, char** args) is startingpoint when running your program.
I args is an array of argc command line arguments.
I int main() is another possibility when no arguments arerequired.
1 #inc lude < i o s t r eam>2
3 i n t main ( ){4 s t d : : cout<<”Easy Going ! ”<<s t d : : e nd l ;5 return 0 ;6 }
54
Introduction to Modern Scientific Programming
The Compiler Model
Steps for writing software
I Open text editor of your choice (e.g. kate). Source files oftenget the extension ".cpp", declarations ".h".
I Every program must have exactly one main function4. This isthe entry point for program execution.
I We will be using the GNU C++ compiler g++. Simple codecan be compiled by typing "g++ my program.cpp".
I The compiler produces an executable file. This can be run bytyping "./my program".
I In case your software contains bugs, you might want to debugit, e.g. by using ddd.
4libraries dont need to
55
Introduction to Modern Scientific Programming
The Compiler Model (cont.)
Write Source Compile Files
Run Preprocessor Run Compiler Run Linker
ErrorOK
Generating object code Generating binaryResolving Macros,
Templates, Defines
ErrorOK
Correct Code
C++ Compiler
Test Code
Start End
Use Debugger
Using Makefiles
for larger projects
56
Introduction to Modern Scientific Programming
MakefilesI A Makefile lets you define all commands required for
building a program in an easier to manage and repeatable way.I You normally only have to type "make" which automatically
executes the building process defined in the file "Makefile".
The structure is (commands have to be preceded by a TAB !):
TARGET T: REQUIRES X, Y, ZCOMMAND
Example:
# link command:my_program: my_source.o
g++ my_source.o -o my_program
# compilation commands:my_source.o: my_source.cpp
g++ -c my_source.cpp -o my_source.o57
Introduction to Modern Scientific Programming
A Better make: SCons
I SCons5 is a modern replacement for make.
I It is based on the Python scripting language, making it morepowerful and comprehensible.
I SCons files are named "SConstruct".
I Start building process by typing "scons".
1 # B u i l d ” m y p r o g r a m ” f r o m s o u r c e ” m y s o u r c e . c p p ”
2 env=Envi ronment ( )3 env . Program ( ’ my program ’ , ’ my source . cpp ’ )
or
1 # B u i l d ” m y p r o g r a m ” f r o m l i s t o f s o u r c e s
2 env . Program ( ’ my program ’ , [ ’my A . cpp ’ , ’my B . cpp ’ ] )
5www.scons.org
58
Introduction to Modern Scientific Programming
C++ overview
I First commercial availability in 1985.
I C++ has evolved into being the most widely used - and assuch the certainly best supported - programming language.
I Operating systems, word processors, games, scientificapplications etc. are written in C++.
I These days freely available on literally every platform (e.g.GNU compiler).
I Hundrets of books, thousands of libraries and many tools likeIDEs6, compilers, debuggers, profilers, editors etc.
6integrated development environments
59
Introduction to Modern Scientific Programming
C++ overview (cont.)
Conceptually C++[4]
I is a general purpose programming language
I is a better C
I supports data abstraction
I supports object oriented programming
I facilitates generic programming.
60
Introduction to Modern Scientific Programming
OO Principles
Data Abstraction/Encapsulation Objects communicate throughtheir interfaces, i.e. data and logic are not revealedto other objects.
Polymorphism Objects can appear in ”multiple forms” while at thesame time providing identical interfaces.
Inheritance Properties (i.e. attributes and methods) can beinherited/derived from one object to others.
public Methods
Data
Methods
Methods
Object Interface
class A
class B
Objects are called classes in C++,defined by the class keyword.
61
Introduction to Modern Scientific Programming
OO Principles (inheritance/polymorphism)
Shape is base class (generalisation), Circle and Rectangle areconcretisations:
Shape
#color :Color
+ getArea ():double
+ draw ():void
+ setColor ():void
Circle
+ getArea ():double
Rectangle
+ getArea ():double
+ rotate (angle :double ):void
Generalisation
I They inherit methods andattributes of Shape.
I Existing methods can beoverloaded for providing a newimplementation of a derivedinterface: Is-A relationship.
I New attributes and methodscan be added: Is-Like-Arelationship.
62
Introduction to Modern Scientific Programming
OO Principles (cont.)
Some OO advantages
I Reusability of code by abstraction, component models,inheritance.
I Maintainability: Easier extension of data and methods.
I Working with objects supports clean software engineering:Data and methods combined.
63
Introduction to Modern Scientific Programming
A Gentle Introduction to C++
Note
C++ is not C.Learn C++ (i.e. design classes!), not C (i.e. procedural design).
Most important entity is a class:
1 c l a s s Tes tC l a s s {2 } ;
It can contain member variables and methods. These can bedeclared being private or public7.Public methods and variables define the interface of a class.Private methods and variables can only be accessed by methods ofthe class.
7or protected
64
Introduction to Modern Scientific Programming
C++ Class example
I C++ classes can be used like normal built-in types.
I Access public methods or variables of a class by "." qualifier.
1 c l a s s Tes tC l a s s {2 pub l i c :3 void p r i n t S t r i n g ( s t d : : s t r i n g s ){4 s t d : : cout<<”This i s the s t r i n g : ” << s + ”\n” ;5 }6 } ;7
8 i n t main ( ){9 Tes tC l a s s t c ; / / d e f i n e v a r i a b l e t c
10 t c . p r i n t S t r i n g ( ”Hi ! ” ) ; / / c a l l m e t h o d o f c l a s s
11 return 0 ; / / e n d p r o g r a m
12 }
65
Introduction to Modern Scientific Programming
C++ Class example (cont.)
I For nontrivial classes, declaration and implementation shouldbe separated.
I Put declaration in "YourClass.h", definition in"YourClass.cpp".
I Include declaration in all files that need to use your class with"#include <YourClass.h>". Esp. "YourClass.cpp" needs it!
1 / / d e c l a r a t i o n i n ” t e s t c l a s s . h ”
2 c l a s s Tes tC l a s s {3 pub l i c :4 void p r i n t S t r i n g ( s t d : : s t r i n g s ) ;5 } ;
1 / / d e f i n i t i o n i n ” t e s t c l a s s . c p p ”
2 void Tes tC l a s s : : p r i n t S t r i n g ( s td : : s t r i n g s ){3 s t d : : cout<<”This i s the s t r i n g : ” << s + ”\n” ;4 }
66
Introduction to Modern Scientific Programming
C++ Class example (cont.)
MyClass.h
MyClass 1 declaration
MyClass 2 declaration
MyClass1.cpp
MyClass 1 implementation
MyClass2.cpp
MyClass 2 implementation
MyProgram.cpp
int main(){
MyClass2 mc2;
...
}
MyClass1.obj
MyClass2.obj
MyProgram.obj
MyProgram
Compile Link
67
Introduction to Modern Scientific Programming
Class Inheritance
I Inherited methods may be overloaded, i.e. a newimplementation is provided.
1 c l a s s A{2 pub l i c :3 s t d : : s t r i n g getName ( ) { return ” Ba s e c l a s s ” ; }4 i n t Counter ;5 } ;6
7 c l a s s B: pub l i c A{8 s t d : : s t r i n g getName ( ) { return ” Der i v ed C l a s s ” ; }9 } ;
10 / / m a i n ( ) o m i t t e d
11 B b ;12 b . Counter = 1 ;13 s t d : : cout << b . getName ( ) ;
68
Introduction to Modern Scientific Programming
Class Lifecycle
I The definition of a variable of a class is called instantiation.
I The variable itself is an instance of the respective class.
I When a class is instantiated, one of its constructors is called.
I A constructor should setup the classes state, i.e. its variables.
I When an instance, i.e. a variable of class type, is destroyed,the class’ destructor is called.
I A destructor should clean up a classes state, e.g. write itsvariables to a file.
I In case you do not provide either or both of these methodtypes for your class, the compiler will implicitely define adefault constructor and/or destructor.
69
Introduction to Modern Scientific Programming
Class Lifecycle: Constructor
I A class can have several constructors.
I They must be distinguished by their parameter list.
I Constructors do not have a return type.
I They qualify as constructors by having the same name as theclass.
1 c l a s s Coun t i ngC l a s s {2 pub l i c :3 Coun t i ngC l a s s ( ) : Counter ( 0 ) {}4
5 Coun t i ngC l a s s ( i n t c ) : Counter ( c ) {}6
7 pr i va te :8 i n t Counter ;9 } ;
70
Introduction to Modern Scientific Programming
Class Lifecycle: Constructor (cont.)
The syntax for variable initialisationCountingClass():Counter(0) {}
is8 equivalent toCountingClass() { Counter = 0; }
Constructors - and all other functions! - can be given defaultargumentsCountingClass(int c = 0):Counter(c) {}
The last example combines the two previously defined constructorsinto one constructor.
When providing a default parameter, all other parameters to theright also need to have a default argument.void myfunc(int i, int j = 4, int k = 10);
8most of time
71
Introduction to Modern Scientific Programming
Class Lifecycle: Destructor
I A class has exactly one destructor.
I The destructor does not have a return type and also has noarguments.
I It gets the same name as the class, headed by a tilde ~.
1 c l a s s Coun t i ngC l a s s {2 pub l i c :3 ˜ Coun t i ngC l a s s ( ){4 s t d : : cout << ”Counter : ” << Counter ;5 s t d : : cout << ” Terminat ing .\ n” ;6 }7
8 pr i va te :9 i n t Counter ;
10 } ;
72
Introduction to Modern Scientific Programming
Inheritance and Construction/Destruction
I The base class’ ctor9 is called automatically before the derivedclass’ ctor is executed.
I The base class’ dtor is called automatically after the derivedclass’ dtor is executed10.
I If you want a different constructor than the default one of thebase class to be called, use:
1 c l a s s B : pub l i c A{2 pub l i c :3 / / B ’ s c t o r c a l l s A ’ s c t o r A ( s t r i n g , i n t )
4 B( s td : : s t r i n g s ) :A( s , 3 )5 { }6 } ;
9ctor is a common abbreviation for constructor, dtor means destructor10this can be circumvented by using a virtual destructor (will discuss later)
73
Introduction to Modern Scientific Programming
The C++ Class: OverviewFeatures of a class TestClass:
I When instantiated, one of the class’ constructors are called.
I When disposed the unique class’ destructor is called.
I Each class can obtain several constructors namedTestClass(YOUR-PARAMS) and one destructor~TestClass(). These methods have no return type.
I A class can be inherited from a base class.
I Methods and data are contained in it!
instantiate class access class’ members destroy class (implicitely)
constructor called destructor called
74
Introduction to Modern Scientific Programming
Using Library Classes
For many common tasks C++ already provides functions, classesand data structures in the standard library.
I Classes of the standard library are included in thenamespace11 "std".
I Namespaces provide a logical naming organisation.
I Namespace qualifier is "::".
I You access classes of the standard library by a preceding"std::".
I Recall: To use classes defined in other files, use "#include<otherclass>" to include the declarations you intend toaccess.
I "using namespace std;" can be used to automaticallyaccess the standard namespace.
11Namespaces will (somewhen. . . ) be explained in the appendix in more detail.
75
Introduction to Modern Scientific Programming
stdlibThe std::string Class
I Provides a poweful character aggregation type.I Operators "=, +=, +, []" are overloaded, see example.I Some methods: string substr(uint from, uint to),
int find(string s, frompos = 0),uint size(), insert(uint pos, string s).
1 #inc lude < s t r i n g >2 using namespace s t d ;3
4 i n t main ( ){5 s t r i n g s1 ( ” s t r i n g 1 ” ) ;6 s t r i n g s2 = ” s t r i n g 2 ” ;7 s t r i n g s3 = s1 + s2 ;8 s2 += s1 ;9 cout << s2 [ s2 . f i n d ( ”1” ) ] ;
10 return 0 ; }
76
Introduction to Modern Scientific Programming
stdlibThe iostreams ClassStandard C++’s iostreams provide functions for reading andwriting to files and the console.
I Include declarations of functions and data:"#include<iostreams>"
I Streams declare operators << for writing and >> for reading.I Stream names: cout, cin (console output and input).
1 / / p r e p r o c e s s o r d i r e c t i v e f o r d e c l a r a t i o n i n c l u s i o n
2 #inc lude < i o s t r eam>3 #inc lude < s t r i n g >4 using namespace s t d ;5 s t r i n g s = ”whats up ” ;6 i n t main ( ){7 s t r i n g name ;8 c i n >> name ;9 cout << s << name << ”?” << end l ; }
77
Introduction to Modern Scientific Programming
stdlibReading and Writing Files
File streams are declared in the fstream classes.
I Include declarations by "#include <fstream>".
I In analogy to std::cin, std::cout use std::ifstream,std::ofstream (input/output file stream) with operators<<, >>.
I Constructors of ifstream, ofstream take string containingfilename to be used, e.g.ifstream in("testfile.txt");
I Use "bool getline(ifstream, string)" for reading a fileline-wise: Read line from ifstream into string, returningtrue when successful, false otherwise (e.g. ”end of file”).
78
Introduction to Modern Scientific Programming
stdlibReading and Writing Files: Example
1 #inc lude < s t r i n g >2 #inc lude < f s t r eam>3 using namespace s t d ;4
5 i n t main ( ){ / / c o p y f i l e
6 / / o p e n f o r r e a d i n g
7 i f s t r e am i n ( ” F i l e . t x t ” ) ;8 / / o p e n f o r w r i t i n g
9 o f s t r e am out ( ”Copy . t x t ” ) ;10 s t r i n g s ;11 whi le ( g e t l i n e ( in , s ) )12 out << s << ”\n” ;13 return 0 ;14 }
Note: getline() discards newline character so we add it again.
79
Introduction to Modern Scientific Programming
stdlibThe Container std::vectorThe standard library contains generic implementations forcommonly used containers named vector, list, deque, set,map, hash, queue, stack and string.
I Containers provide dynamic memory management at runtime!I std::vector is the probably best known container.I Use of conventional arrays should be discarded in favour of
std::vector.I As a template class it can contain objects of arbitrary type.I Usage: "#include <vector>" first, then
"std::vector<TYPE> my var;".
1 #inc lude < vec to r >2 using namespace s t d ;3 / / m a i n ( ) o m i t t e d
4 vec to r <int > i n t v e c ;5 vec to r <s t r i n g > s t r i n g v e c ;6 vec to r <Tes tC la s s > t e s t c l a s s v e c ;
80
Introduction to Modern Scientific Programming
stdlibThe Container std::vector (cont.)
I uint size() returns the number of elements,
I push back(x) inserts an element x ,
I clear() removes all elements,
I index operator [pos] returns element at pos.
1 / / i n c l u d e s a n d m a i n ( ) o m i t t e d
2 s t r i n g s1 = ” f e ed ” ;3 s t r i n g s2 = ”me” ;4 vec to r <s t r i n g > s t r v e c ;5 s t r v e c . push back ( s1 ) ;6 s t r v e c . push back ( s2 ) ;7 s t r v e c . push back ( s t r i n g ( ” ! ” ) ) ;8 f o r ( unsigned i n t i = 0 ; i < s t r v e c . s i z e (); ++ i )9 cout << s t r v e c [ i ] << ” ” ;
81
Introduction to Modern Scientific Programming
stdlibThe Container std::map
I Recall: The std::vector can be used as a versatilesubstitute for conventional arrays.
I It is a sequential container, i.e. a linear list of elements thatcan be accessed by their index.
I A std::map is an associative container.
I It contains pairs of <key,value> elements.
I A map can be accessed by element keys.
I We will use the std::pair<keyType,valueType> templatefor creating elements to put in a std::map.
82
Introduction to Modern Scientific Programming
stdlibThe Container std::map (cont.)
1 / / i n c l u d i n g < i o s t r e a m > < u t i l i t y > , < s t r i n g > , < map >
2 using namespace s t d ;3 / / m a i n ( ) o m i t t e d
4 map<s t r i n g , int > my map ;5 pa i r <s t r i n g , int > pr1 ( ”A” , 1 0 ) ;6 pa i r <s t r i n g , int > pr2 ;7 pr2 . f i r s t = ”B” ;8 pr2 . second = 100 ;9 my map . i n s e r t ( pr1 ) ;
10 my map . i n s e r t ( pr2 ) ;11 my map . i n s e r t ( pa i r <s t r i n g , int >(”AnotherWay” ,−10)) ;12 my map [ ” C r e a t e I t ” ] = 1234 ;13
14 cout << my map [ ”B”] << my map [ ” C r e a t e I t ” ]15 << my map [ ”C” ] ;
83
Introduction to Modern Scientific Programming
stdlibIterators
I Iterators provide a generic way for accessing containerelements.
I They generalise the notion of pointers12.
I Each standard container implicitely defines appropriateiterator types, e.g. std::vector<int>::iterator orstd::map<string,int>::iterator.
I One gets iterators to the start/end of a container by callingmethods begin()/end() on a container instance.
I Access the element pointed to by an iterator it bydereferencing it: "*it".
I This convention is common to all containers!
12which we will encounter shortly
84
Introduction to Modern Scientific Programming
stdlibIterators: Example
1 typedef vec to r <char > : : i t e r a t o r v e c i t ;2 typedef map<s t r i n g , int > : : i t e r a t o r map i t ;3 / / g i v e n a v e c t o r < c h a r > v a r i a b l e ” v e c ”
4 f o r ( v e c i t i t = vec . beg i n ( ) ; i t != vec . end (); ++ i t )5 cout << ∗ i t ;6
7 / / g i v e n a map < s t r i n g , i n t > v a r i a b l e ” s i m ”
8 f o r ( map i t i t = sim . beg in ( ) ; i t != vec . end (); ++ i t )9 cout << (∗ i t ) . f i r s t << ”\ t ” << (∗ i t ) . second ;
I When accessing element pairs stored in std::map (and otherassociative container) by an iterator, use: "(*it).first"and "(*it).second" for getting key and value.
I The typedef keyword is used to define a new data type:Assign a convenient alias to a complicated typename.
85
Introduction to Modern Scientific Programming
stdlibPreliminary Summary: Containers
Container Features
I One can put arbitrary data types into containers, due totemplates, e.g.std::list<string>, std::vector<MyClass>,std::map<int,string>.
I All containers share a common concept of iterating theircontents, due to iterators, e.g.std::list<string>::iterator,std::vector<MyClass>::iterator,std::map<int,string>::iterator.
This gives but a hint of how powerful C++ actually is!We will see later that algorithms can be generalised as well, basedon these concepts.
86
Introduction to Modern Scientific Programming
Introduction: Pointers and References
We still need to learn some basic C++ language syntax for dealingwith variables and functions: The pointer operator "*" and thereference operator "&".
PointerA pointer is a variable that contains the physical address ofanother defined variable. It can be used for
I passing a variable to a function for modification,
I pointing into an array (the ”target element” can be selectedby adding integer values to the pointer) and
I to hold the address of a dynamically allocated variable.
87
Introduction to Modern Scientific Programming
Introduction: Pointers and References (cont.)
Reference
I A reference is a substitute name for another variable13.
I Example: When modifying a reference called Aref of a variablecalled A, then the value of A itself is changed.
I This is an important concept for passing variables to functionsand initialising/assigning pointers.
13functionally speaking
88
Introduction to Modern Scientific Programming
Referenceof something
int i1 = 3
int i2 = 10
string s="1
2
3
4"
(class )A a
attributes ...
methods ...
char c[3]=’a’
’b’
’c’
0x08bf0000
0x08bf0002
0x08bf0004
0x08bf004 + 3
I Whenever you define a variable, memory isallocated for it.
I A position in memory is described by a memoryaddress.
I You can get the address of a variable by usingthe reference operator &.
1 i n t i 1 ;2 s t d : : cout << s t d : : hex << & i 1 ;
Would print: "0x08bf0000".
Note: You can change the number base of theoutput streams by sending bin, oct, dec, hex tothem.
89
Introduction to Modern Scientific Programming
Reference: Function Parameter Passing Semantics
Opponent methods for passing variables to functions:
pass-by-value copy variable, so original variable can not bechanged by the function being called or
pass-by-reference pass reference to original variable, enablingmodification of original variable by called function.
1 void modi fy ( i n t i , i n t & j ){2 i = 1 ; j = 2 ;3 }4 / / m a i n ( ) o m i t t e d
5 i n t I = 0 ;6 i n t J = 0 ;7 modi fy ( I , J ) ; / / = > I = = 0 , J ==2
90
Introduction to Modern Scientific Programming
Pointerto something
I Pointers point to a variable (i.e. a basic type variable or aclass instance).
I A pointer is defined by "TYPE* pointerVar;".
I The pointer by itself does not own memory for a value of therespective type – unless you allocate memory for it.
I It can point to another variable definition:"int* intP = &i1;".
I For accessing the value a pointer points to one has todereference it: "*intP = 4;" (This is same syntax as with iterators!)
1 i n t i 1 = 3 ;2 i n t ∗ i n tP = & i 1 ;3 ∗ i n tP = 4 ;4 cout << ” i 1 : ” << i 1 << ”==” << ∗ i n tP ;
91
Introduction to Modern Scientific Programming
Pointer (cont.)
I When pointing to an array, one can navigate the pointer byadding integer values to it.
1 i n t i n tA [ 1 0 ] ;2 i n t ∗ i n tP = intA ; / / p o i n t e r t o 1 s t e l e m e n t
3 i n tP + 5 ;4 ∗ i n tP = 6 ; / / s e t 6 t h e l e m e n t
Beware: Invalid Pointers
Pointers that are not initialised with a valid address or that pointto an invalid address, e.g. by uncautious pointer arithmetic, willeasily result in a fatal program error (”segmentation fault”).
92
Introduction to Modern Scientific Programming
Freestore Management: new and delete
I One commonly needs to dynamically create variables atrun-time.
I This can be done by the keywords new, delete.
I new allocates, i.e. reserves, memory for a variable,
I delete frees memory for a previously allocated variable.
I For allocating arrays, use new[], delete[].
Memory Management Rule
Each new has to have a corresponding delete!All allocated variables have to be freed before exiting the program.
Memory leaks are often hard to track down and cause serioustrouble. An improved mechanism for memory management is thenotion of smart pointers.
93
Introduction to Modern Scientific Programming
Reference, Pointer, new and delete Example
1 / / m a i n ( ) o m i t t e d
2 unsigned i n t s i z e ;3 long ∗ lP ;4 count << ”Memory s i z e : ” ; c i n >> s i z e ;5 / / a l l o c a t e m e m o r y
6 lP = new long [ s i z e ] ;7 f o r ( unsigned i n t i =0; i<s i z e ; ++ i )8 lP [ i ] = s i z e− i ;9
10 unsigned i n t c e n t r e = ( unsigned i n t ) ( s i z e / 2 ) ;11 long ∗ lP2 = lP + c en t r e ;12 ∗ lP2 = 0 ;13
14 / / f r e e m e m o r y
15 de lete [ ] lP ;
94
Introduction to Modern Scientific Programming
Reference, Pointer, new and delete Example (cont.)
Calling a member function of a class instance a pointed to by aP:I (*a).testFunc() is equivalent toI a->testFunc()
1 #inc lude < c l a s sA . h>2 / / m a i n ( ) o m i t t e d
3 A a ; / / i n s t a n c e o f c l a s s A
4 A∗ aP1 ; / / p o i n t e r t o c l a s s A
5 A∗ aP2 ;6
7 aP1 = &a ;8 (∗ aP1 ) . t e s tFunc ( ) ;9
10 aP2 = new A;11 aP2−>t e s tFunc ( ) ;12 de lete aP2 ;
95
Introduction to Modern Scientific Programming
Complex Data Types
I One can define complex data types as an aggregate of other(simple) type variables.
I Either use class or, which is more appropriate, struct(ure).
I A struct is equivalent to a class with default public accessqualifier, i.e.
1 s t ruc t typeA{2 i n t x , y ;3 } ;4
5 c l a s s typeB{6 pub l i c :7 i n t x , y ;8 } ;
are equivalent declarations.
96
Introduction to Modern Scientific Programming
Complex Data Types Example
1 s t ruc t typeA{2 i n t x [ 2 ] ;3 s t r i n g name ;4 } ;5
6 i n t myfunc ( typeA& a ){7 cout << a . name << ” : ” << a . x [ 0 ] ;8 return a . x [ 1 ] ;9 }
10
11 i n t main ( ){12 typeA a ;13 a . x [ 0 ] = 1 ; a . x [ 1 ] = 3 ;14 a . name = ” s t r u c t u r e ” ;15 return myfunc ( a ) ;16 }
97
Introduction to Modern Scientific Programming
Introduction: Inheritance/Polymorphism Revisited
[1] Shape
−color :Color
+ draw ():void
[2] Circle
+ draw ():void
[3] Rectangle
+ draw ():void
1 C i r c l e c ;2 Rec tang l e r ;3 c . draw ( ) ; / / c a l l s C i r c l e : : d r a w ( )
4 r . draw ( ) ; / / c a l l s R e c t a n g l e : : d r a w ( )
I Classes 2, 3 inherit public/protected methods andmember variables of base class 1.
I Constructor of 1 is automatically invoked before ctor of 2/3.
I Destructor of 1 is automatically invoked after dtor of 2/3.
I 2,3 overload draw() method with own implementation.
I 2 and 3 are of type 1 ( Is-A relationship).
98
Introduction to Modern Scientific Programming
Introduction: Inheritance/Polymorphism (cont.)
[1] Shape
−color :Color
+ draw ():void
[2] Circle
+ draw ():void
[3] Rectangle
+ draw ():void
1 void drawShape ( Shape& shape ){2 shape . draw ( ) ; / / c a l l s S h a p e : : d r a w ( ) !
3 }4 / / m a i n ( ) o m i t t e d
5 C i r c l e c ;6 drawShape ( c ) ;
Call of drawShape(c) is valid, but Shape::draw()implementation gets called instead of Circle::draw()!
I Normally function calls are fixed at compile-time: draw() iscalled on a variable of type Shape.
I For the previous example to work, we need late binding so thecalled method draw() is determined at run-time. This thenaccounts for methods being overloaded by subclass Circle.
I Late binding is essential to polymorphism and can beenforced by the virtual keyword.
99
Introduction to Modern Scientific Programming
OO: PolymorphismVirtual Functions
Polymorphism is a very powerful concept:
I We can define functions requiring a shape argument and passthem a circle, a rectangle or subsubclasses likeRoundedRectangle etc..
For Overloading Class Functions
. . . they need to be declared with the virtual keyword in thebase class.(being virtual in all subclasses then is implicit, hence, optional)
Rules of thumb:
I Whenever you intent to overload methods of a base class,declare them being virtual.
I You normally really want to do the previous!
I If a class has a virtual method, the destructor should also bevirtual (in case it’s defined).
100
Introduction to Modern Scientific Programming
OO: PolymorphismVirtual Functions (cont.)
1 c l a s s A{2 pub l i c :3 v i r t u a l i n t get ID ( ) { return 1 ; }4 } ;5
6 c l a s s B : pub l i c A{ / / c l a s s B I s −A c l a s s A
7 pub l i c :8 i n t get ID ( ) { return 2 ; }9 } ;
Recall:
I Class A is baseclass of class B.
I Class B Is-A class A, overloading method getID().
101
Introduction to Modern Scientific Programming
OO: PolymorphismVirtual Functions (cont.)
1 void p r i n t ID (A& a r e f ){2 s t d : : cout << ” ID i s : ” << a r e f . get ID ( ) ;3 }4
5 void main ( ){6 / / d e c l a r e / d e f i n e v a r i a b l e a , b
7 A a ;8 B b ;9 p r i n t ID ( a ) ; / / p r i n t s ” 1 ”
10 p r i n t ID ( b ) ; / / p r i n t s ” 2 ” !
11 }
102
Introduction to Modern Scientific Programming
A Note on Parameter Passing
We discussed function parameter copy and reference semantics.Be aware that
I Default semantic is to copy variable/object values totemporary objects when passing arguments, i.e. the followingwill produce a class A copy (a copy) of subclass B (my b):
1 void func (A a copy ){ cout << a copy . get ID ( ) ; }2 [ . . . ]3 B my b ;4 func (my b ) ;
a param then provides the A::getID() implementation, i.e.not subclass B::getID().
I Hence, passing by reference is needed when using subclasseswith overloaded methods.
Rule: You normally will want to to pass objects by reference!
103
Introduction to Modern Scientific Programming
Operator Overloading
I Most operators can be overloaded for your own purposes, e.g.
+, -, *, /, ++, --, +=, -=, *=, /=, ^, (), [],=, ==, !, !=, <<, >>.
I Syntax like normal function declaration but with keywordoperator.
I Operator overloading should be used with care: do notconfuse the user of your class by defining non-intuitivebehaviour of operators.
1 / / i m p l e m e n t e q u a l i t y o p e r a t o r o f c l a s s A
2 bool A : : operator==(A& a ){3 return get ID () == a . get ID ( ) ; }4
5 / / i m p l e m e n t ( ) o p e r a t o r o f c l a s s F u n c t i o n
6 double Funct i on : : operator ( ) ( double x ){7 return x∗x ; }
104
Introduction to Modern Scientific Programming
this and Returning References
I Keyword this can be used in member functions, denoting apointer to the current class instance.
1 bool A : : operator==(A& a r e f ){2 / / ” t r u e ” i f a r e f i s s a m e i n s t a n c e
3 return th i s == & a r e f ; }4 [ . . . ]5 A a , b ;6 cout << ”Equal : ” << (a==a) << ”\ t ” << (a==b ) ;
I this is commonly applied for returning a reference to thecurrent instance when overloading operators ++, --, +=,-=, *=, /=, i.e. whenever we want to return the (modified)object itself.
105
Introduction to Modern Scientific Programming
Operator OverloadingExample
1 s t ruc t I n t e g e r {2 / / d e f a u l t c t o r
3 I n t e g e r ( i n t i = 0 ) : v a l ( i ) {}4
5 / / c o p y c t o r
6 I n t e g e r ( I n t e g e r & i ) : v a l ( i . v a l ) {}7
8 / / a d d i t i o n r e t u r n i n g n e w o b j e c t
9 I n t e g e r operator+( i n t & i )10 { I n t e g e r temp ( v a l+i . v a l ) ; return temp ; }11
12 / / s e l f − a s s i g n m e n t r e t u r n i n g r e f e r e n c e
13 I n t e g e r & operator+=(I n t e g e r & i )14 { v a l+=i . v a l ; return ∗ t h i s ; }15
16 i n t v a l ; } ;
106
Introduction to Modern Scientific Programming
Operator OverloadingExample (cont.)
1 / / a d d i 2 t o i 1 , m o d i f y i n g i 1 b y t h i s
2 void add ( I n t e g e r & i1 , I n t e g e r & i 2 ){3 / / a d d i 2 t o i 1 r e f e r e n c e
4 i 1 += i 2 ;5 }6 / / m a i n ( ) o m i t t e d
7 I n t e g e r i 1 ( 1 ) , i 2 ( 2 ) ; / / i 1 = = 1 , i 2 ==2
8 add ( i 1 += 3 , i 2 ) ; / / i 1 ==5
This only works as we return a reference of this with"Integer& operator+=(Integer&)".
107
Introduction to Modern Scientific Programming
Smart Pointers
I Conventional C pointers like ”int* pInt” are sometimescalled dumb pointers.
I They often cause major problems during development, esp.when using dynamic memory management.
Use the smart alternative when a pointer is inevitable:A smart pointer
I manages ownership of a dynamically created object and
I provides automatic memory deallocation.
Pointer Rules
Avoid pointers whenever possible. (It’s for your own good.)Allocated memory should be managed by a smart pointer.
108
Introduction to Modern Scientific Programming
Smart Pointers (cont.)
I Smart pointers mimic dumb pointer by providing operators"*" and "->" for dereferencing it.
I Their main purpose is to provide automatic lifetime control.
I Create a new object with new and pass the pointer to a smartpointer.
I You don’t have to take care of destruction (i.e. delete) anymore!
STL’s only smart pointer14 is the std::auto ptr. Betterimplementations can be found in the boost library.
14this will hopefuly change in the next standard
109
Introduction to Modern Scientific Programming
STL’s std::auto ptr
Usage:
1 s t d : : au t o p t r <int> i n tP (new in t ) ;2 s t d : : au t o p t r <A> a (new A) , b ;3 / / m a i n ( ) o m i t t e d
4 ∗ i n tP = 3 ;5 a−>get ID ( ) ;
std::auto ptr caveat:
I ownership transfer semantic for copy operation.
1 b=a ; / / a s s i g n a n d t r a n s f e r o w n e r s h i p
2 b−>get ID ( ) ; / / v a l i d
3 a−>get ID ( ) ; / / i n v a l i d !
Strictly single ownership of the allocated object!
110
Introduction to Modern Scientific Programming
STL’s std::auto ptr (cont.)
STL containers may internally rearrange their elements, therebyde- and reallocating objects.Hence, due to single ownership policy:
Note
std::auto ptr is not appropriate for STL containers! Useboost::shared ptr instead.
May nevertheless be useful for source-sink models:
1 void s i n k ( au to p t r <A> aP ) ;2 / / m a i n ( ) o m i t t e d
3 au to p t r <A> s ou r c e (new A) ;4 s i n k ( s ou r c e ) ; / / e a t s u p s o u r c e
111
Introduction to Modern Scientific Programming
boost’s Smart Pointers
The boost library is a collection of free extensions to the C++standard library. We will use smart pointers and the linear algebrapackage µBLAS later.boost offers smart pointers for
shared ownership boost::shared ptr, boost::shared array:multiple pointers can share the same reference.The last living pointer will destroy the reference.
strictly single ownership boost::scoped ptr,boost::scoped array: Single ownership, notcopyable, cannot be used in STL containers.
weak reference boost::weak ptr: pointer is owned by aboost::shared ptr, boost::shared array andis not affected by the weak reference. Termination ishandled by owning pointer(s).
112
Introduction to Modern Scientific Programming
boost’s Smart Pointers (cont.)
You will need to include boost’s declarations by:
1 #inc lude <boos t / s h a r e d p t r . hpp>2 #inc lude <boos t / s h a r e d a r r a y . hpp>
Usage is similar to std::auto ptr:
1 boos t : : s h a r e d p t r <A> a ;2
3 { / / d e f i n e l o c a l s c o p e
4 boos t : : s h a r e d p t r <A> b (new A) ;5 a = b ;6 b−>get ID ( ) ; / / a a n d b v a l i d
7 } / / b o u t o f s c o p e − > d t o r
8
9 a−>get ID ( ) ; / / s t i l l v a l i d !
113