Presentation is loading. Please wait.

Presentation is loading. Please wait.

GETTING STARTED WITH C++ ID1218 Lecture 082009-11-23 Christian Schulte Software and Computer Systems School of Information and Communication.

Similar presentations


Presentation on theme: "GETTING STARTED WITH C++ ID1218 Lecture 082009-11-23 Christian Schulte Software and Computer Systems School of Information and Communication."— Presentation transcript:

1 GETTING STARTED WITH C++ ID1218 Lecture 082009-11-23 Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

2 L08, 2009-11-23ID1218, Christian Schulte 2 Overview  Functions  Pointers  Arrays  Objects

3 L08, 2009-11-23ID1218, Christian Schulte 3 Reading Suggestions  All of you thorough reading of chapters 0 to 4 take a peek at chapter 11

4 Functions L08, 2009-11-23 4 ID1218, Christian Schulte

5 L08, 2009-11-23ID1218, 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

6 L08, 2009-11-23ID1218, Christian Schulte 6 Function Example int maxx(int x, int y) { return (x > y) ? x : y; }

7 L08, 2009-11-23ID1218, 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

8 L08, 2009-11-23ID1218, 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

9 L08, 2009-11-23ID1218, 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);

10 L08, 2009-11-23ID1218, 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

11 L08, 2009-11-23ID1218, 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

12 L08, 2009-11-23ID1218, 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)

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

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

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

16 L08, 2009-11-23ID1218, 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

17 L08, 2009-11-23ID1218, 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

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

19 L08, 2009-11-23ID1218, 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

20 Arrays L08, 2009-11-23 20 ID1218, Christian Schulte

21 L08, 2009-11-23ID1218, 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!

22 L08, 2009-11-23ID1218, 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

23 L08, 2009-11-23ID1218, 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!

24 L08, 2009-11-23ID1218, 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

25 L08, 2009-11-23ID1218, 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

26 L08, 2009-11-23ID1218, 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

27 L08, 2009-11-23ID1218, 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)

28 L08, 2009-11-23ID1218, Christian Schulte 28 Vectors and C++ Strings  Vectors are C++ arrays #include automatic resize automatic memory management copied when passed as parameters  Strings #include same advantages as above support for comparison, copying on assignment, …  Please read book about both vectors and strings

29 Parameter Passing L08, 2009-11-23 29 ID1218, Christian Schulte

30 L08, 2009-11-23ID1218, 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

31 L08, 2009-11-23ID1218, 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

32 L08, 2009-11-23ID1218, 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);

33 Pointers L08, 2009-11-23 33 ID1218, Christian Schulte

34 L08, 2009-11-23ID1218, 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

35 L08, 2009-11-23ID1218, 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;

36 L08, 2009-11-23ID1218, Christian Schulte 36 Pointers Illustrated…  After declaration int x = 10; int y = 7; int* p; p points somewhere (unitialized) (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = ????…

37 L08, 2009-11-23ID1218, Christian Schulte 37 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…) (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = ????…

38 L08, 2009-11-23ID1218, Christian Schulte 38 Redirecting…  Let p point to location of x p = &x; (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = &x = 100…

39 L08, 2009-11-23ID1218, Christian Schulte 39 Assigning…  Assign object pointed to by p a value *p = 5; (&x) 100 x = 5 (&y) 104 y = 7…… (&p) 200 p = &x = 100…

40 L08, 2009-11-23ID1218, Christian Schulte 40 Redirecting…  Let p point to location of y p = &y; (&x) 100 x = 5 (&y) 104 y = 7…… (&p) 200 p = &y = 104…

41 L08, 2009-11-23ID1218, Christian Schulte 41 Assigning…  Assign object pointed to by p a value *p = 99; (&x) 100 x = 5 (&y) 104 y = 99…… (&p) 200 p = &y = 104…

42 L08, 2009-11-23ID1218, 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

43 L08, 2009-11-23ID1218, 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;

44 L08, 2009-11-23ID1218, 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

45 L08, 2009-11-23ID1218, 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);

46 Arrays are Pointers L08, 2009-11-23 46 ID1218, Christian Schulte

47 L08, 2009-11-23ID1218, 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

48 L08, 2009-11-23ID1218, Christian Schulte 48 Pointer Arithmetic  Static array int a[3] = {3,2,1}; (a+0) 100 3 (a+1) 104 2…1 (a+2) 108 … …

49 L08, 2009-11-23ID1218, Christian Schulte 49 Pointer Arithmetic  Static array int a[3] = {3,2,1}; a[2] = *(a+1); (a+0) 100 3 (a+1) 104 2…2 (a+2) 108 … …

50 L08, 2009-11-23ID1218, 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)

51 L08, 2009-11-23ID1218, Christian Schulte 51 Computing String Length unsigned int sl(char* s) { unsigned int n = 0; while (s[n] != 0) n++; return n; }  Use pointer s as array sl("test test");

52 L08, 2009-11-23ID1218, Christian Schulte 52 Computing String Length unsigned int sl(char* s) { char* b = s; while (*s != 0) s++; return s-b; }  Use pointer s as pointer sl("test test");

53 L08, 2009-11-23ID1218, Christian Schulte 53 Computing String Length unsigned int sl(const char* s) { const char* b = s; while (*s != 0) s++; return s-b; }  Do not allow that string passed as argument is modified the content is const, not the pointer!

54 Objects and Classes L08, 2009-11-23 54 ID1218, Christian Schulte

55 L08, 2009-11-23ID1218, Christian Schulte 55 An Integer Cell class IntCell { private: int x; public: IntCell(int y=0) { x=y; } int get() { return x; } void set(int y) { x=y; } };

56 L08, 2009-11-23ID1218, Christian Schulte 56 Reminder: Access Control  public: visible to everybody  protected: visible to subclasses only inheritance explained later  private: visible only to defining class  default is private!

57 L08, 2009-11-23ID1218, Christian Schulte 57 Creating an Integer Cell  To be used locally IntCell c; cout << c.get() << endl; c.set(4); cout << c.get() << endl ;

58 L08, 2009-11-23ID1218, Christian Schulte 58 Creating an Integer Cell  Use globally: allocate memory on heap IntCell* c = new IntCell(5); cout get() << endl; c->set(42); refer to by pointer! do not forget to delete: delete c ;

59 L08, 2009-11-23ID1218, Christian Schulte 59 Accessors vs Mutators  Fundamental difference set:changes object state (mutator) get:does not change state (accessor)  In C++ accessors need to be declared const int get() const { return x; } compiler enforces that state is not changed well, can be controlled with const-cast…

60 L08, 2009-11-23ID1218, Christian Schulte 60 Accessors int square(const IntCell* ic) { return ic->get()*ic->get(); }  Requires that get is declared const! due to const IntCell*

61 L08, 2009-11-23ID1218, Christian Schulte 61 Implicit Type Conversion  The following code works IntCell ic; ic = 4; due to constructor used for type conversion  If not desired, declare as explicit: explicit IntCell(int y=0) { x=y; } only for one parameter constructors

62 L08, 2009-11-23ID1218, Christian Schulte 62 Initializer Lists  Rewrite constructor to IntCell(int y=0) : x(y) {} after colon: comma separated list in order of declaration of members  Old version first initialize with default constructor for member then assign value  New version only initialized  Matters for non primitive data members!

63 L08, 2009-11-23ID1218, Christian Schulte 63 Passing Objects as Parameters  By default, objects are copied void test(IntCell m) { m.set(7); } IntCell n; test(n); cout << n.get() << endl; still prints zero! copying can be expensive if not wanted: pass by reference or const reference!

64 L08, 2009-11-23ID1218, Christian Schulte 64 Copying and Assignment  Copying is controlled by copy constructor IntCell(const IntCell& c) : x(c.x) {}  Assignment is controlled by assignment operator IntCell& operator=(const IntCell& c) { if (this != &c) x=c.x; return *this; }  These are synthesized by compiler if missing required for resource management

65 L08, 2009-11-23ID1218, Christian Schulte 65 A Different IntCell  Maintain integer via pointer class IntCell { private: int* x; public: IntCell(int y=0) : x(new int) { *x = y; } … } how to manage the allocated memory?

66 L08, 2009-11-23ID1218, Christian Schulte 66 Copy Constructor IntCell(const IntCell& c) : x(new int) { *x = *c.x; }  Used for parameter passing  Used for initialization (assume c is IntCell ) IntCell d(c);

67 L08, 2009-11-23ID1218, Christian Schulte 67 Assignment Operator IntCell& operator=(const IntCell& c) { if (this != &c) { delete x; x = c.x; } return *this; }  Returns an IntCell to allow assignment sequences a = b = c;

68 L08, 2009-11-23ID1218, Christian Schulte 68 Destructor ~IntCell() { delete x; }  When object is deleted by delete (for heap allocated) by going out of scope (for automatically allocated) destructor is invoked for resource management

69 L08, 2009-11-23ID1218, Christian Schulte 69 Default Constructor  A constructor with no arguments (or all arguments with default values) automatically generated, if no constructors provided  Important for initialization IntCell c; invokes the default constructor

70 Summary L08, 2009-11-23 70 ID1218, Christian Schulte

71 L08, 2009-11-23ID1218, Christian Schulte 71 Summary  Functions parameter passing: by value (copy), by reference, by constant reference  Arrays are pointers pointer arithmetic  Objects constructors: default, copy assignment operator destructor


Download ppt "GETTING STARTED WITH C++ ID1218 Lecture 082009-11-23 Christian Schulte Software and Computer Systems School of Information and Communication."

Similar presentations


Ads by Google