1 / 71

Getting Started With C++

Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden. Getting Started With C++. ID1218 Lecture 08 2009-11-23. Overview. Functions Pointers Arrays Objects.

brie
Download Presentation

Getting Started With C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Christian Schulte cschulte@kth.se Software andComputer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden Getting Started With C++ ID1218 Lecture 08 2009-11-23

  2. Overview • Functions • Pointers • Arrays • Objects ID1218, Christian Schulte

  3. Reading Suggestions • All of you • thorough reading of chapters 0 to 4 • take a peek at chapter 11 ID1218, Christian Schulte

  4. Functions ID1218, Christian Schulte

  5. Function Definition • Function definition contains • return type • function name • parameter list • body • Function can be called given function name and appropriate parameters • Function can only be defined once ID1218, Christian Schulte

  6. Function Example int maxx(int x, int y) { return (x > y) ? x : y; } ID1218, Christian Schulte

  7. Function Invocation • Print maximum of two numbers cout << maxx(43,27) << endl; • Uses call-by-value • Parameters need not be of type int • automatic cast long int • possibly with warning ID1218, Christian Schulte

  8. Function Overloading • The same function name can be used multiply with different types in parameter list double maxx(double x, double y) { return (x>y) ? x : y; } • Complicated set of rules describe which definition is chosen • Overloading with different return type only not allowed ID1218, Christian Schulte

  9. Function Declarations • Every function needs to be declared prior to invocation • declared, but not defined! • can be declared multiply • A function declaration is done by giving a function prototype int maxx(int, int); or int maxx(int a, int b); ID1218, Christian Schulte

  10. Default Parameters • Default values can be given for formal parameters • if function has declaration, in declaration • if function has only definition, in definition • only allowed as last formal parameters • Assume that maxx is often used with 0 as second argument int maxx(int, int = 0); Then the following invocation is legal int z = maxx(-45); • In this case, definition remains unchanged ID1218, Christian Schulte

  11. Inline Functions • Overhead of function call be significant: maxx is good example • Give function definition an inline directive inline int maxx(int x, int y) { … } • Invocation of function is replaced by body • Definition must be textually before first invocation • Compilers will also inline other, small functions ID1218, Christian Schulte

  12. Separate Compilation • Structure larger programs into separate files • each file contains some functions: better structure • each file can be compiled independently: save compilation time during development • Header file • contains declarations and definitions of inline functions • file name extensions: .h, .hh • Implementation file • contains definition of functions (implementation) ID1218, Christian Schulte

  13. Header File maxx.h /* * Declaration of maximum function */ int maxx(int, int); ID1218, Christian Schulte

  14. Implementation File maxx.cpp #include "maxx.h" int maxx(int x, int y) { return (x > y) ? x : y; } ID1218, Christian Schulte

  15. Main File main.cpp #include <iostream> #include "maxx.h" int main() { std::cout << maxx(47,23) << std::endl; return 0; } ID1218, Christian Schulte

  16. Putting Everything Together • Compile each implementation file independently g++ -c main.cpp g++ -c maxx.cpp • creates the files main.o and maxx.o • contain object code but require linking • Put everything together (linking) g++ main.o maxx.o –o main.exe ID1218, Christian Schulte

  17. Include Each Header at Most Once • Remember: inline functions must be defined not only declared before usage • Remember: at most one definition! • what if header is included from other header files • possibly having multiple definitions of same function • also: why read same header more than once? • Use preprocessor (also macro processor) to guarantee at-most-once inclusion • define a preprocessor variable when included • test whether preprocessor variable not already defined • choose reasonably unique name ID1218, Christian Schulte

  18. Fixed Header File maxx.h /* * Declaration of maximum function */ #ifndef __MAXX_H__ #define __MAXX_H__ int maxx(int, int); #endif ID1218, Christian Schulte

  19. Organizing Compilation • How to organize compilation • recompilation needed if included header file changes • compilation can be time-consuming: > 1000 files? • only recompile what is needed • Use make: express dependencies among files • files only recompiled, if dependencies change • rules for how to perform compilation • .cpp  .o • .o  .exe • later (first lab session) more ID1218, Christian Schulte

  20. Arrays ID1218, Christian Schulte

  21. C-style Arrays • C-style arrays int a[42]; creates an array of 42 integers • access cout << a[1]; • assignment a[1] = a[2]+a[3]; • ranges from a[0] to a[41] • Dimension of array must be constant • can be evaluated at compile time to constant (eg 2*4) • illegal int a[n] where n is variable! ID1218, Christian Schulte

  22. Using Arrays as Parameters int find_max(int a[], int n) { int m = a[0]; for (int i = 1; i<n; i++) if (a[i] > m) m=a[i]; return m; } • Array of arbitrary size int a[] • requires to pass size as extra parameter int n ID1218, Christian Schulte

  23. Using Arrays as Parameters int find_max(int a[42]) { int m = a[0]; for (int i = 1; i<42; i++) if (a[i] > m) m=a[i]; return m; } • Supports only arrays statically known to have size 42! ID1218, Christian Schulte

  24. Allocating Arrays • What if size is not known statically • memory for array must be allocated from heap • after use, memory must be explicitly freed • C++ style memory management • use new [] and delete [] • special versions for arrays • normal versions to be used later for objects ID1218, Christian Schulte

  25. Allocating Arrays • Allocate an array of integers with size n new int[n]; • Free memory array (no matter its size or type) delete [] a; • The following does not work int a[] = new int[n]; • a must have known size, or used as parameter • use pointers rather than arrays ID1218, Christian Schulte

  26. Primitive Arrays of Constants • Initialize arrays in declaration • declare array to be not assignable const int DIM[] = {31,28,31,30,31,30, 31,31,30,31,30,31}; • declares array of size 12 ID1218, Christian Schulte

  27. C-Style Strings • Use arrays of chars! • Often const char s[] = "A C-string."; • contains all letters given plus • 0 at the end (end-of-string marker) • has size 12 (additional 0) ID1218, Christian Schulte

  28. Vectors and C++ Strings • Vectors are C++ arrays • #include <vector> • automatic resize • automatic memory management • copied when passed as parameters • Strings • #include <string> • same advantages as above • support for comparison, copying on assignment, … • Please read book about both vectors and strings ID1218, Christian Schulte

  29. Parameter Passing ID1218, Christian Schulte

  30. Call By-value • Default mechanism already seen • works by copying: straightforward for primitive types • but copying also for objects: to be discussed later! • What if one return value is not enough? • use call by-reference ID1218, Christian Schulte

  31. Call By-reference • Function to exchange to values, first attempt (wrong): void exc(int a, int b) { int t = a; a=b; b=t; } • just works on copies passed to exc • need to pass references instead ID1218, Christian Schulte

  32. Call By-reference • Function to exchange to values (correct): void exc(int &a, int &b) { int t = a; a=b; b=t; } • a and b are passed by reference • effect is on actual parameters int x = 4; int y = 5; exc(x,y); • constants are not allowed as actual parameters exc(x,5); ID1218, Christian Schulte

  33. Pointers ID1218, Christian Schulte

  34. Pointers • Are a consequence that memory management is not abstracted away • Erlang and Java: all variables hold references to values, operations are performed implicitly on value • C and C++ distinguish • objects (also primitive values) • pointers: values which point to memory address of objects ID1218, Christian Schulte

  35. Pointers • Declaring a pointer to an integer int* p; • Let p point to address of x int x = 5; p = &x; • & is called unary address-of operator • Read value at pointer: prints 5 cout << *p; • * is called unary dereference operator • Store value at memory referenced at p: prints 7 *p = 7; cout << x; ID1218, Christian Schulte

  36. (&x) 100 (&y) 104 (&p) 200 x = 10 y = 7 … … p = ???? … Pointers Illustrated… • After declaration int x = 10; int y = 7; int* p; • p points somewhere (unitialized) ID1218, Christian Schulte

  37. (&x) 100 (&y) 104 (&p) 200 x = 10 y = 7 … … p = ???? … Segmentation Fault or Bus Error… • Assign object pointed to by p a value *p = 124; • but: not necessarily, p can also point to some other location (overrides other variables contents…) ID1218, Christian Schulte

  38. (&x) 100 (&y) 104 (&p) 200 x = 10 y = 7 … … p = &x = 100 … Redirecting… • Let p point to location of x p = &x; ID1218, Christian Schulte

  39. (&x) 100 (&y) 104 (&p) 200 x = 5 y = 7 … … p = &x = 100 … Assigning… • Assign object pointed to by p a value *p = 5; ID1218, Christian Schulte

  40. (&x) 100 (&y) 104 (&p) 200 x = 5 y = 7 … … p = &y = 104 … Redirecting… • Let p point to location of y p = &y; ID1218, Christian Schulte

  41. (&x) 100 (&y) 104 (&p) 200 x = 5 y = 99 … … p = &y = 104 … Assigning… • Assign object pointed to by p a value *p = 99; ID1218, Christian Schulte

  42. Common Idioms • Testing that pointers refer to same location p1 == p2 • Testing that objects pointed to have same value *p1 == *p2 • Use NULL for ptr not pointing anywhere const int NULL = 0; • use in initialization, tests, etc ID1218, Christian Schulte

  43. Heap Memory Management • Get memory from heap int* p = new int; • allocate memory block big enough for one int • After use, release delete p; ID1218, Christian Schulte

  44. Getting It Wrong • Forget to delete • program crashes when running out of memory • Delete to early • lucky case: program crashes due to OS knowing that memory has been freed • unlucky case: already reused, arbitrary things can happen! • Delete twice • runtime error ID1218, Christian Schulte

  45. Call-by-reference in C • C does not provide references: use pointers instead void exc(int *a, int *b) { int t = *a; *a=*b; *b=t; } • effect is on values pointed to int x = 4; int y = 5; exc(&x,&y); ID1218, Christian Schulte

  46. Arrays are Pointers ID1218, Christian Schulte

  47. Arrays are Pointers • C-Style arrays are basically pointers • point to beginning of array • Array access a[i] translates to *(a+i) • Common idiom: pointer arithmetic • pointer +/- integer: offset to pointer • pointer – pointer: distance between pointers ID1218, Christian Schulte

  48. (a+0) 100 (a+1) 104 3 2 … 1 … Pointer Arithmetic • Static array int a[3] = {3,2,1}; (a+2) 108 … ID1218, Christian Schulte

  49. (a+0) 100 (a+1) 104 3 2 … 2 … Pointer Arithmetic • Static array int a[3] = {3,2,1}; • a[2] = *(a+1); (a+2) 108 … ID1218, Christian Schulte

  50. Creating Dynamic Arrays • An array of size n int* a = new int[n]; • Release memory later delete [] a; • never forget the []: important for arrays of objects (calling destructor) ID1218, Christian Schulte

More Related