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

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
GETTING STARTED WITH C++ ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
C++ AND C ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Pointer Data Type and Pointer Variables
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
Chapter 2 Objects and Classes
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Chapter 7: User-Defined Functions II
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Lecture 6 C++ Programming
User-Defined Functions
Chapter 2 Objects and Classes
Advanced Programming Behnam Hatami Fall 2017.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Object Oriented Programming COP3330 / CGS5409
Introduction to Classes
Constructors and Destructors
Constructors and Destructors
9-10 Classes: A Deeper Look.
CS410 – Software Engineering Lecture #5: C++ Basics III
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

GETTING STARTED WITH C++ ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

L08, ID1218, Christian Schulte 2 Overview  Functions  Pointers  Arrays  Objects

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

Functions L08, ID1218, Christian Schulte

L08, 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

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

L08, 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

L08, 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

L08, 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);

L08, 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

L08, 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

L08, 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)

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

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

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

L08, 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

L08, 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

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

L08, 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

Arrays L08, ID1218, Christian Schulte

L08, 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!

L08, 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

L08, 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!

L08, 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

L08, 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

L08, 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

L08, 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)

L08, ID1218, 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

Parameter Passing L08, ID1218, Christian Schulte

L08, 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

L08, 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

L08, 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);

Pointers L08, ID1218, Christian Schulte

L08, 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

L08, 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;

L08, ID1218, 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 = ????…

L08, ID1218, 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 = ????…

L08, ID1218, 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…

L08, ID1218, 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…

L08, ID1218, 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…

L08, ID1218, 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…

L08, 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

L08, 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;

L08, 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

L08, 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);

Arrays are Pointers L08, ID1218, Christian Schulte

L08, 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

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

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

L08, 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)

L08, ID1218, 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");

L08, ID1218, 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");

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

Objects and Classes L08, ID1218, Christian Schulte

L08, ID1218, 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; } };

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

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

L08, ID1218, 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 ;

L08, ID1218, 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…

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

L08, ID1218, 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

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

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

L08, ID1218, 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

L08, ID1218, 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?

L08, ID1218, 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);

L08, ID1218, 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;

L08, ID1218, 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

L08, ID1218, 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

Summary L08, ID1218, Christian Schulte

L08, ID1218, 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