Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel March 23, 2015 Working with C and C++, March 23, 2015 1
Challenges of This Course Heterogeneity of the audience (different level of programming experience, different programming languages, etc.); We assume: Experience in procedural programming (FORTRAN, C, or similar) availability of a notebook with some C++ compiler (Details on installation for win in Tutorial 1) Variety of topics related to C++ selection of topics! General: Giving a lecture on how to swim won t work participants have to jump into water (i.e. program!) Restricted amount of time long-term learning effects not without using C++ for different tasks yourself! Working with C and C++, March 23, 2015 2
What Will be Covered in This Course... Working with C and C++, March 23, 2015 3
Outline of Day 1 Basic usage From text files to binary code header files vs. implementation files Basics of C memory management: data types, pointers, control structures (loops/if/switch) functions call by value vs. reference... From C to C ++ (Extensions) namespaces references... Working with C and C++, March 23, 2015 4
Outline of Day 2 & 3 Object-oriented Programming Concepts/way of thinking Syntax in C++ Object-based Programming Information hiding OO Continued Inheritance (taxonomy) Polymorphism The UML Modeling Language Design Patterns Working with C and C++, March 23, 2015 5
Outline of Day 4 & 5 Advanced Topics Operator Overloading, deep vs. shallow copy Type conversion, explicit (temporary objects) Usage of const File I/O Templates & the Standard Template Library STL Understanding templates (templated function, templated class) The Standard Template Library Using templates and STL for data structures (containers) and algorithms Working with C and C++, March 23, 2015 6
What Will NOT be Covered in This Course...... and is nevertheless interesting/relevant: exception handling assertions details on libraries (static vs. shared) details on design patterns preprocessor commands and macros makefiles & Co. automatic testing (cppunit etc.) automatic code documentation (doxygen, doxys, etc.) debugging with gdb, valgrind & Co. Working with C and C++, March 23, 2015 7
Organisation of This Course Persons: Day 1+2: Tobias Neckel, Roland Wittmann Day 3+4+5: Wolfgang Eckhardt, Tobias Neckel Times: 5 days: 2h lecture + 2h tutorials each Website: General infos: http://www5.in.tum.de/wiki/index.php/ Object-oriented_Programming_in_C%2B%2B_MPE-2015 Examples used on the slides: http://www5.in.tum.de/ lehre/vorlesungen/progcourse/c++/mpe_2015/src/ Working with C and C++, March 23, 2015 8
1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Working with C and C++, March 23, 2015 9
1 Basic Usage Working with C and C++, March 23, 2015 10
1.1 From Text Files to Binary Code as in FORTRAN, source code needs to be compiled: source: http://pages.towson.edu/davani/cosc236/handouts/com-process.html Working with C and C++, March 23, 2015 11
Comments in C / C ++ 1 // one line comment 3 /* 4 several lines 5 */ 7 /** 8 * several lines, autodocutool syntax : 9 * 10 * This file is part of the C++ course. 11 * @author Tobias Neckel, Wolfgang Eckhardt 12 * 13 * @section LICENSE 14 * Copyright (c) 2014 15 * 16 * @section DESCRIPTION 17 * Simple example showing pointer aspects 18 * 19 * compile : g++ -O3 -g array. cpp -o array 20 **/ Working with C and C++, March 23, 2015 12
A First Example 13 # include <iostream > 14 15 int main () { 16 std :: cout << " printing output... " << std :: endl ; 17 std :: cout << " first computation : 5+11= " << 5+11 << std :: endl ; 18 return 0; 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basic_usage/first_example.cpp C / C ++ comes along with lots of useful standard libraries. Libraries provide a lot of useful operations. Examples: iostream math.h Add declarations via include statements ( compiler knows declarations). For (external) libraries in different path: use -I path/to/lib/includes to inlcude Working with C and C++, March 23, 2015 13
Basic Compilation 1 g++ -O3 -g first_example. cpp -o test_executable Working with C and C++, March 23, 2015 14
1.2 Header Files C/C++ distinguishes declaration and definition. Declaration: Tell the compiler what names are available. Definition: Define where the name is stored. Working with C and C++, March 23, 2015 15
A Second Example: More Than One File 13 # include <iostream > 14 # include " computations.h" 15 16 int main () { 17 std :: cout << " adding via function : 5+11= " << add_values (5,11) << std :: endl ; 18 return 0; 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basic_usage/second_example.cpp 1 /** 2 * Here comes some documentation : 3 * Adding two integers and returns the result. 4 */ 5 int add_values ( int a, int b); code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basic_usage/computations.h 1 # include " computations.h" 2 3 int add_values ( int a, int b) { 4 return a+b; 5 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basic_usage/computations.cpp Working with C and C++, March 23, 2015 16
Compilation of Two Files Variant 1: compile & link simultaneously 1 g++ -O3 -g second_example. cpp computations. cpp -o second_v1 Variant 2: Step 1: compile Step 2: link passing the object files to the linker, or passing the library files (a,so) due to the -l argument with -L giving the compiler the library search path. 1 g++ -O3 -g -c second_example. cpp computations. cpp 2 g++ -O3 -g second_example.o computations.o -lm -o second_v2 Working with C and C++, March 23, 2015 17
Naming Conventions for Files type C C ++ implementation.c.cpp.cxx.c.cc header.h.h.hpp.hxx Working with C and C++, March 23, 2015 18
Header Files - Best Practices A good header file (almost) never contains definitions. A good header file has lots of comments (on what a function or object does, not on how) since: other editors of files see it frequently, automatic code documentation tools may/will use it. Each header file is typically accompanied by one implementation file. Frequently, header files contain include guards: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c+ +/MPE_2015/src/basic_usage/include_guards.h Working with C and C++, March 23, 2015 19
1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Working with C and C++, March 23, 2015 20
2 C ++ as an increment of C Working with C and C++, March 23, 2015 21
Properties of C ++ C 99 C++ 98 C <99 <99 C++ Historically: C ++ designed as an increment of C Design/development influenced by other programming languages C ++ contains considerable amount of constructs that are new/redundant compared to C (casts, new vs. malloc,... ) Working with C and C++, March 23, 2015 22
1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Working with C and C++, March 23, 2015 23
3 Basics of C Working with C and C++, March 23, 2015 24
3.1 Built-in Data Types int integer value (signed) short int integer (typ. 16 bytes) long int integer (typ. 32 bytes) unsigned int int (purely positive) double floating point number (double prec.) float floating point number (single prec.) char character bool boolean type (only C ++) Working with C and C++, March 23, 2015 25
Built-in Data Types - int 20 int i; 21 int k; 22 i = 5; 23 k = -1; Here, some C / C ++ syntax obvious: Declaration/definition of variables Assignment of variable values note: = different to == note: garbage value of variable if no assignment! Working with C and C++, March 23, 2015 26
Built-in Data Types - double and float 30 double a; 31 double b; 32 double c; 33 a = 0.145e -07; 34 b = 23.24 e09 ; 35 c = a+b; 36 std :: cout << c << std :: endl ; float analoguous Note: default number of printed digits on command line: 6 (change possible, see streams below) Working with C and C++, March 23, 2015 27
Built-in Data Types - char 49 char x=65, y= B ; 50 51 std :: cout << x << " " << y << std :: endl ; 52 std :: cout << x+y << std :: endl ; Attention: string manipulation etc. cumbersome in C special data type std::string in C ++ Working with C and C++, March 23, 2015 28
Built-in Data Types - bool no real boolean data type in C actually, int is (mis-)used different historic workarounds but: boolean data type in C ++ (true or false) Working with C and C++, March 23, 2015 29
Built-in Data Types & Memory Memory int x; char y; float z; 21: y // one byte 22; z // four bytes 23; 24; 25; 26; x // two bytes? 27; 28: A variable corresponds to memory location and holds a value. Compiler cares for memory layout. Working with C and C++, March 23, 2015 30
Constants 1 i n t ConstantA = 1; 2 double ConstantB = 0. 4 ; 3 double ConstantC = 23.232323; 4 5 void main ( ) { 6... 7 } Constants are treated similar to source code, i.e. translated by the compiler into bit sequences. Some very simple constants can be embedded into the micro codes (assembler). At startup, all others are loaded into the memory. Working with C and C++, March 23, 2015 31
3.2 Memory Organisation (WIN style) Static and global variables (Some) Read-only variables Constants (not user accessible) Code Heap Stack Appl 1 Appl 2 Appl 3 Reserved by OS (adrs $0, typically 128 kb) Working with C and C++, March 23, 2015 32
Memory Organisation for Variables Whole memory per application: split up into segments (or sections). Linker can determine their size. Search for free memory: only done for heap data. Other variables: created (and destroyed) one by one on the stack segment. Exception: Variables not declared within main or any other function, but outside. Those are global/static variables held by a different segment. Each object file holds a specification for the segments (sizes). The linker then merges them into one big memory layout. Working with C and C++, March 23, 2015 33
3.3 Type Inference double float int unsigned int Note: casts from supersets to subsets: may cause compiler warnings! Working with C and C++, March 23, 2015 34
Type Inference - Example 1 15 # include <iostream > 16 17 int main () { 18 19 // Example 1 20 unsigned int u = 2; 21 int i = 1; 22 double d; 23 24 d = (u *10) - 0.32; 25 std :: cout << "d( wu) = " << d << std :: endl ; 26 d = (i *10 + u) - 0.32; 27 std :: cout << "d( wi) = " << d << std :: endl ; 28 u = d * 10; 29 std :: cout << "u = " << u << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/type_inference.cpp Working with C and C++, March 23, 2015 35
Type Inference - Example 2 32 int a1 = 3; 33 int b1 = 4; 34 double c1 = a1 + b1; 35 36 std :: cout << " c1 = " << c1 << std :: endl ; 37 c1 = 7.0; 38 std :: cout << " c1 = " << c1 << std :: endl ; 39 40 double a2 = 3.0; 41 int b2 = 4; 42 int c2 = a2 + b2; 43 44 std :: cout << " c2 = " << c2 << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/type_inference.cpp Working with C and C++, March 23, 2015 36
Type Inference - Type Conversion Pitfall 47 double d0 = 4 / 3; 48 std :: cout << " d0 = " << d0 << std :: endl ; 49 50 double d1 = 4.0 / 3.0; 51 std :: cout << " d1 = " << d1 << std :: endl ; 52 53 double d2 = 4.0 / 3; 54 std :: cout << " d2 = " << d2 << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/type_inference.cpp Working with C and C++, March 23, 2015 37
3.4 Recap: Scopes, Loops & Branches The concept of the scope: A variable has to be declared within the same brackets { }. Otherwise, compiler searches within the enclosing brackets (not within the neighbours). The brackets define a scope. The outer brackets define an outer scope. Some compilers allow the programmer to redefine variables within subscopes. This hides variables they are not overwritten. Working with C and C++, March 23, 2015 38
Recap: Loops Loops render the programming style applicative programming. Types of loops: while, do-while, for. Concept: should be known. Syntax: 1 while ( expression ) { 2 / / something i n t e l l i g e n t 3 } 4 5 do { 6 / / something i n t e l l i g e n t 7 } while ( expression ) ; Working with C and C++, March 23, 2015 39
Recap: The For Loop 1 f o r ( i n t a=0; a<20; a++) { 2 / / something i n t e l l i g e n t 3 } for statements: opens a new scope Statement int a: creates a new variable (loop counter) within this scope Statement a<20: termination criterion (evaluated before the upcoming iteration) Statement a++: increment of the loop counter Working with C and C++, March 23, 2015 40
Recap: Branches if-then-else constructs: 20 double a =2.5; 21 double b =3.8; 22 23 double max ; 24 if (a < b) { 25 max = b; 26 } 27 else { 28 max = a; 29 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/branches.cpp comparison operators: <, >, <=, >=, ==,!= logical operators:!, &&, Working with C and C++, March 23, 2015 41
Recap: Branches (2) switch statement: 33 char c; 34 std :: cout << " please type a character :" << std :: endl ; 35 std :: cin >> c; 36 37 switch (c) { 38 case a : 39 case A : 40 std :: cout << " you typed A " << std :: endl ; 41 break ; 42 case b : 43 case B : 44 std :: cout << " you typed B " << std :: endl ; 45 break ; 46 default : 47 std :: cerr << "l. 47: unknown character!" << std :: endl ; 48 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/branches.cpp Attention: do not forget the break statement! Working with C and C++, March 23, 2015 42
3.5 Functions Syntax of function definitions: 1 r e t u r n t y p e functionname ( paramtype paramname ) { 2 / / do something i n t e l l i g e n t 3 } Functions define a scope due to the brackets { } (basis block). Variables of other scopes are not defined within the function. Working with C and C++, March 23, 2015 43
Functions - Examples 17 void nothing ( void ); // function prototype 18 void nothing2 (); // function prototype 19 void timesx ( int x); // function prototype 20 int area ( int a, int b); // function prototype 21 22 void nothing ( void ) { 23 std :: cout << " do nothing :-)" << std :: endl ; 24 } 25 void nothing2 () { 26 std :: cout << " do nothing again " << std :: endl ; 27 } 28 void timesx ( int x) { 29 for ( int i =1; i <=x; i ++) { 30 std :: cout << "*" << std :: endl ; 31 } 32 } 33 int area ( int a, int b) { 34 return a*b; 35 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/functions.cpp Working with C and C++, March 23, 2015 44
17 double foo ( double a, double h) { 18 if (h ==0) { 19 return 0.0; 20 } 21 if (a ==0) 22 return ; // error 23 // do something complicated with a and h 24 return a /10.0; 25 } 26 27 void foo2 ( double a, double h) { 28 //... 29 return 1; // error 30 } Return Statements code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/functions2.cpp Return statement makes the application leave the current function. accepts one argument: the return value (if it is not a void function). may be everywhere in the function. But: multiple return statements often are considered to be bad style. Working with C and C++, March 23, 2015 45
What is the main Function? 21 double change_sign ( double b) { 22 // change sign and return new value 23 } 24 25 int main ( int argc, char * argv []) { 26 // do something : change signs 27 change_sign (5.3) ; 28 29 return 0; 30 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/functions3.cpp Execution always set to the main function. main function returns 0 if it has been successful (error code). This is a UNIX convention. UNIX command line arguments: argc holds amount, argv is 1D array of strings. Working with C and C++, March 23, 2015 46
3.6 Call-by-value vs. Call-by-Reference Questions to be tackled: What happens with parameters in functions when being called? Can functions modify outside variables? What do you know already? In C/C++, parameters (arguments) are passed call-by-value. Functions work on copies of the original variables. The original variables are saved away on the call stack. As soon as the operation terminates, the old variable values are restored. Working with C and C++, March 23, 2015 47
Call-by-value & Return Statement 15 # include <iostream > 16 17 int multiplybytwo ( int x) { 18 x = x *2; 19 return x; 20 } 21 22 23 int main () { 24 25 int x = 10; 26 int b = multiplybytwo (x); 27 std :: cout << " main (): x = " << x << std :: endl ; 28 std :: cout << " main (): b = " << b << std :: endl ; 29 30 x = multiplybytwo (x); 31 std :: cout << " main (): x = " << x << std :: endl ; 32 33 return 0; 34 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/call_by_value_return.cpp The return statement takes the value of the function s copy and writes it to the left-hand side of the function invocation. Working with C and C++, March 23, 2015 48
3.7 Pointers Memory 21: 22; 123 // int a 23; 24; 25; 26; 27; 28: The memory is enumerated using an integer. Pointers are variables that hold the memory number (address) instead of a value. 1 / / holds an i n t ; 2 i n t a ; 3 / / holds address o f an i n t 4 i n t * p ; Working with C and C++, March 23, 2015 49
Pointers and Addresses The * operator declares a pointer. 19 int a = 123; 20 int *p; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/pointer.cpp The & operator returns the address of a variable (address operator or reference operator). 22 p = &a; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/pointer.cpp The * operator makes an operation act on the location a pointer points to instead of the pointer itself (dereferencing operator). 26 a += 10; 27 std :: cout << "a = " << a << std :: endl ; 28 (* p) += 10; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/pointer.cpp Working with C and C++, March 23, 2015 50
Pointers and the Memory Memory 21: 22; 123 // int a 23; 24; 22 // pointer p 25; 26; 27; 28: int a; a = 123; int *p; p = &a; a++; p++; (*p)++; *p++; // try this at home Working with C and C++, March 23, 2015 51
3.8Arrays: Array Declaration Memory 21: 22; // grade[0] 23; // grade[1] 24; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 1 double grade [ 4 ] ; 2 3... Working with C and C++, March 23, 2015 52
Array Access 1 double grade [ 4 ] ; Memory 21: 22; // grade[0] 23; // grade[1] 24; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 2 3... 4 5 grade [ 0 ] = 1. 3 ; 6 grade [ 2 ] = 3. 3 ; 7 grade [ 3 ] = 1. 0 ; 8 grade [ 1 ] = 4. 0 ; Depending on the context: [] defines the size of an array (definition) [] gives access to individual entries of an array (access). Working with C and C++, March 23, 2015 53
Arrays & Pointers 1 double grade [ 4 ] ; 2 grade [ 0 ] = 1. 3 ; 3 grade [ 2 ] = 3. 3 ; 4 grade [ 3 ] = 1. 0 ; 5 grade [ 1 ] = 4. 0 ; 6 7 double * p = grade ; 8 i f ( grade [ 0 ] = = * p )... / / always t r u e 9 i f ( grade [ 1 ] = = * ( p+1) )... / / always t r u e Name of array == pointer to the first element of array Array element access: internally implies pointer arithmetics and dereferencing Attention pointers: range checks (size of array) not automatically! Working with C and C++, March 23, 2015 54
19 double matrix [4][4]; 20 Multidimensional Arrays 21 for ( int i=0; i <4; i++) { 22 for ( int j=0; j <4; j++) { 23 // conditional assignment 24 matrix [i][ j] = i==j? 1.0 : 0.0; 25 std :: cout << "m[" <<i<<"][" <<j<<"]=" << matrix [i][ j] << std :: endl ; 26 } 27 } 28 matrix [2][1] = 5.0; 29 // matrix [12] = 12.0; // does not compile! 30 * matrix [1] = 12.0; 31 * matrix [17] = 12.0; // compiles, but...!? try compile with -O0 code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/array_multidim.cpp What is the semantics of the for loop? Multidimensional arrays basically are flat arrays. C/C++ uses row-major format (different to FORTRAN), i.e. if you pass arrays to FORTRAN code you might have to transpose the array first. Working with C and C++, March 23, 2015 55
Dynamic Arrays ( C ++ Style) 1 double * grades = new double [ 4 5 ] ; 2 3 d e l e t e [ ] grades ; We can create arrays on the heap. Size might be a variable, too. Corresponding delete has to be a delete[]. delete without brackets just deletes the first value. There is a performance reason for two different delete operators. If we omit delete, we will get a memory leak. If we use the array after delete or before new, it points to garbage (remember: grades is only a pointer) probably crash. Working with C and C++, March 23, 2015 56
Dynamic Arrays - Memory Static and global variables (Some) Read-only variables Constants (not user accessible) Code Heap Stack Appl 1 Appl 2 Appl 3 Reserved by OS (adrs $0, typically 128 kb) Working with C and C++, March 23, 2015 57
1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Working with C and C++, March 23, 2015 58
4 From C to C ++ (Extensions) Working with C and C++, March 23, 2015 59
4.1 Namespaces: Multiple Declarations with Different Context 14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 /** 18 * Calculates force between two particles ( Lennard - Jones ) 19 */ 20 double getforce ( const double & distance ); 21 # endif // _IDENTIFIER_FOR_HEADER_A_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_a_no.h 14 // This is header B 15 # ifndef _IDENTIFIER_FOR_HEADER_B_H_ 16 # define _IDENTIFIER_FOR_HEADER_B_H_ 17 /** 18 * Calculates force between two particles ( WCA model ) 19 */ 20 double getforce ( const double & distance ); 21 # endif // _IDENTIFIER_FOR_HEADER_B_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_b_no.h Sometimes, functions and variables have the same name as they were developed by different authors and written into different files. It is very difficult to distinguish between these names, i.e. we Working with C and C++, March 23, 2015 60
14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 namespace lennardjones { 18 /** 19 * Calculates force between two particles ( Lennard - Jones ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 # endif // _IDENTIFIER_FOR_HEADER_A_H_ Namespaces (2) code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_a.h 14 // This is header B 15 # ifndef _IDENTIFIER_FOR_HEADER_B_H_ 16 # define _IDENTIFIER_FOR_HEADER_B_H_ 17 namespace wca { 18 /** 19 * Calculates force between two particles ( WCA model ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 # endif // _IDENTIFIER_FOR_HEADER_B_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_b.h Namespaces: group variables, constants, and functions into logic Wolfgangsubsets. Eckhardt, Tobias Neckel: Object-oriented Programming in C++ Working with C and C++, March 23, 2015 61
Using Namespaces 14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 namespace lennardjones { 18 /** 19 * Calculates force between two particles ( Lennard - Jones ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 # endif // _IDENTIFIER_FOR_HEADER_A_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_a.h 14 // This is the implementation 15 # include " lennardjones.h" 16 17 double lennardjones :: getforce ( const double & distance ) { 18 \ ldots 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/c_to_c++/namespaces_a.cpp Namespaces are predecessors of the identifier. Namespaces can be embedded into each other. Working with C and C++, March 23, 2015 62
17 int multiplybytwo ( int & x) { 18 x = x *2; 19 return x; 20 } 21 22 int main () { 23 24 int x = 10; 25 int b = multiplybytwo (x); 26 std :: cout << " main (): x = " << x << std :: endl ; 27 std :: cout << " main (): b = " << b << std :: endl ; 28 29 x = multiplybytwo (x); 30 std :: cout << " main (): x = " << x << std :: endl ; 31 32 return 0; 33 } 4.2 Call-by-reference code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/call_by_value_reference.cpp The & operator is the reference operator. It tells C/C++ to pass the argument with call-by-reference semantics. Then, C/C++ does not create a copy, but the operation works on Wolfgang Eckhardt, the Tobias original Neckel: Object-oriented variable. Programming in C++ Working with C and C++, March 23, 2015 63
4.3 Using C Libraries in C ++ C 99 C++ 98 C ++: Large standard library in comparison to C In principle, all C headers in C ++ usable Naming conventions of headers: 1 # i n c l u d e <math. h> => # i n c l u d e <cmath> 2 # i n c l u d e <s t d l i b. h> => # i n c l u d e <c s t d l i b > Much more in the upcoming days. Working with C and C++, March 23, 2015 64
5Backup some stuff that may be interesting but is not covered in the lecture Working with C and C++, March 23, 2015 65
Default Arguments of Functions 1 void foo ( i n t a=3) ; 2 void bar ( ) ; 3 void bar ( i n t b=3) ; / / not allowed 4 void tee1 ( i n t c, double d =2.0) ; 5 void tee2 ( i n t c =2, double d ) ; / / not allowed 6 void tee3 ( i n t c =2, double d =4.0) ; 7 8... 9 foo ( ) ; 10 foo ( 7 ) ; 11 tee3 ( ) ; 12 tee1 ( 1 ) ; 13 tee1 ( 1, 4. 0 ) ; C ++ supports default arguments. Overloaded functions may not work! All default arguments have to be at the end of the argument list. Working with C and C++, March 23, 2015 66
Pointer Syntax The pointer operator binds to the right neighbour. 1 i n t a ; 2 i n t * b1 ; 3 i n t * b2 ; 4 i n t * b3 ; 5 i n t * c1, c2 ; 6 i n t * c3, * c4 ; 7 i n t * c5, c6 ; 8 i n t * c7, * c8 ; 9 i n t * * c9 ; 10 11 c7 = c8 ; 12 c7 = * c8 ; / / does not work with a l l compilers 13 * c7 = c8 ; / / does not work with a l l compilers 14 * c7 = * c8 ; By the way, often people write int* p=0; to make the pointer point to nothing. However, also int* p = 20; would be fine (and for almost 100 percent is a bug). Working with C and C++, March 23, 2015 67
Pointers and Scopes 1 i n t * p ; 2 f o r ( i n t i =0; i <2; i ++) { 3 i n t a = 2 * i ; 4 p = &a ; 5 6 std : : cout << a << std : : endl ; 7 std : : cout << * p << std : : endl 8 } 9 std : : cout << a << std : : endl ; / / does t h i s work? 10 std : : cout << * p << std : : endl ; / / does t h i s work? With pointers, we can violate the end-of-scope rules, i.e. we can access variables that do not exist anymore. This is the principle of all these buffer overrun malware codes. Working with C and C++, March 23, 2015 68
Array Arguments 19 double computeaverage ( double grade [], int numberofgrades ) { 20 //... 21 } 22 23 double computeaverage ( const double grade [], int numberofgrades ) { 24 //... 25 } 26 27 double computeaverage ( const double * grade, int numberofgrades ) { 28 //... 29 } 30 31 double computeaverage ( const double * const grade, int numberofgrades ) { 32 //... 33 } 34 35 double computeaverage ( double const * const grade, int numberofgrades ) { 36 //... 37 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/array_arguments.cpp This time, the user is not allowed to modify any entry of grade. Working with C and C++, March 23, 2015 69
Pitfalls 19 int gradesbsc, gradesmsc [5]; 20 21 gradesmsc [5] = 2.3; 22 gradesmsc [3]++; 23 int * p0 = gradesmsc ; 24 int * p1 = & gradesmsc [0]; 25 int * p2 = & gradesmsc [1]; 26 gradesmsc ++; // does not work 27 p2 ++; // arrrgh 28 29 return 0; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/mpe_2015/src/basics_c/array_pitfalls.cpp Working with C and C++, March 23, 2015 70
Outlook C/C++ Arrays vs. FORTRAN FORTRAN is claimed to be the language for linear algebra as it is faster. FORTRAN does not provide pointers and dynamic data structures. Consequently, compiler can keep track of who has access where. Consequently, compiler can optimise aggressively (it tries to keep book of all possible values an array could have side-effect!). So, it is all a matter of exclusivity and the const operator. Working with C and C++, March 23, 2015 71