Advanced Software Engineering with C++ Templates Administrative - - PowerPoint PPT Presentation

advanced software engineering with c templates
SMART_READER_LITE
LIVE PREVIEW

Advanced Software Engineering with C++ Templates Administrative - - PowerPoint PPT Presentation

Advanced Software Engineering with C++ Templates Administrative Issues Thomas Gschwind <thg at zurich dot ibm dot com> About me Lecturer at Universitt Zrich Researcher at IBM Interests Machine Learning Programming


slide-1
SLIDE 1

Advanced Software Engineering with C++ Templates

Administrative Issues

Thomas Gschwind <thgatzurichdotibmdotcom>

slide-2
SLIDE 2

About me

§ Lecturer at Universität Zürich § Researcher at IBM § Interests

  • Machine Learning
  • Programming Languages
  • Software Engineering

§ Enjoying to Teach

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

2

slide-3
SLIDE 3

Agenda

§ Administrative Issues

  • The name of the game
  • Schedule
  • Lectures, Exercises, Exam

§ The game of the name

  • Classes, User-Defined Types, and Namespaces
  • C++ Standard Library: Basic Input and Output, Strings, Containers, Iterators
  • Templates Primer
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

3

slide-4
SLIDE 4

Prerequisites

§ Programming Languages

  • Basic knowledge of object-oriented programming
  • Some knowledge of C (pointers, memory management helpful)
  • Alternatively: Java, or Python

§ For students in the third semester or later

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

4

slide-5
SLIDE 5

The Name of the Game

§ We look at the C++ Programming Language

  • The language features and how they can be used
  • The Standard Library and how it uses the features from C++
  • Examples are small and focus on using features of C++

§ C++ allows developers to use different programming paradigms

  • Procedural programming
  • Object-based programming (templates, static polymorphism)
  • Object-oriented programming (inheritance, dynamic polymorphism)

§ Languages Features of Special Interest

  • Typing
  • Strong vs. weak typing
  • Static vs. dynamic typing
  • Templates
  • Exception Handling
  • Standard Library
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

5

slide-6
SLIDE 6

It’s Rude to be Alive When “No One” Wants You

§ C++ is a C-based language that is infamous for being cryptic

  • Many C developers find it too high-level and having too much overhead
  • Java/Python/… developers find it too low-level

§ Actually there are many Open-Source projects that use C++

  • Tensorflow, Tesseract
  • Mysql
  • Many KDE applications (The widget library (Qt) is implemented in C++)
  • Some Gnome applications

§ C++ provides instructions to influence low-level code generation

  • Today’s computer consume little power and are blazingly fast
  • Why would we care?
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

6

slide-7
SLIDE 7

Loads of Applications Requiring C++

§ Anything requiring loads of CPU

  • Machine learning
  • Big Data Management
  • Analyzing images uploaded to facebook

(identifying problematic content, faces, etc.)

§ Anything to be executed on “small” microprocessor

  • Arduino UNO:

ATmega@16MHz, 2KB SRAM, 1KB EEPROM, 32KB Flash

  • Raspberry Zero:

Single core ARM@1GHz, 512MB memory

  • Many many more

Arduino UNO SDK uses C++ Provides 32k Flash

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

7

slide-8
SLIDE 8

Embedded Devices

§ Anything to be executed on battery-driven processors

  • Your programs takes twice the time
  • Your battery lasts half as long max.
  • Power consumption is quadratic to frequency
  • This is why Android’s dalvikvm is implemented in C++
  • Apple chose Objective C for everything

§ Smartwatches

  • Today they last 1-4 days depending on vendor
  • An efficient program really is important
  • Don’t want to lug around a watch with extra battery
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

8

slide-9
SLIDE 9

More Embedded Devices

§ Anything to be executed on battery-driven processors

  • Now imagine we want to move our embedded

system around…

  • Robots, worse, helicopter, quadrocopter, we

need to lift our battery as well

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

9

slide-10
SLIDE 10

Introduction

§ Historically speaking,

  • C++ is an Algol like programming language

(like Pascal, or Java without OO features)

  • C++ builds on the C language of which it is a superset

(except for comments, struct, enum, …)

§ C++ adds several features to C such as

  • Inheritance
  • Templates
  • Exceptions

§ C++ supports different programming paradigms

  • Procedural programming
  • Object-based programming
  • Object-oriented programming
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

10

slide-11
SLIDE 11

Topics Covered (approximately)

§ Lecture 1

  • Classes, User-Defined Types, Namespaces
  • Templates, Template Specialization
  • Standard Library: Input/Output, Strings, Iterators

§ Lecture 2

  • Traits
  • Separate Compilation, Makefiles

§ Lecture 3

  • Memory Management
  • Standard Library Algorithms, Lambda Functions
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

11

slide-12
SLIDE 12

Topics Covered (cont’d)

§ Lecture 4

  • Template Implementations
  • Tag Dispatching (Compile-Time Algorithm Inference)
  • Inheritance

§ Lecture 5

  • Liskov Substitution Principle
  • Exception Handling
  • Library Initialization

§ Lecture 6

  • Standard Library: Input and Output Formatting
  • Template Metaprogramming
  • Repetitorium
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

12

slide-13
SLIDE 13

Organization & Schedule

§ Announcements and discussions

  • Announcements: http://www.gschwinds.net/teaching/cpp/
  • Discussions: Discussion Forum in OLAT

§ Approx. 6 lectures, 3 hours each (plus 1 backup)

  • Fri. 14:45-18:00 BIN-2.A.01 (including 15min break)
  • For a complete schedule, please check the course web site

§ Exercise submissions and Exam

  • Exercises to be presented by randomly selected students

in the next lecture

  • Exam on Fri. Jan. 22, 16:00 online
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

13

slide-14
SLIDE 14

Grading

§ Exercises handed out after every lecture

  • Examination in the next lecture
  • Show your solution to the exercise
  • Answer questions about your solution and the concepts used in the exercise

§ Exam at the end of the course

  • Most likely written (online exam), potentially oral exam
  • Approx. 50-70% theory, 30-50% practical questions

§ Grading

  • Exercises determine 1/3 of the final grade
  • Exam determines 2/3 of the final grade
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

14

slide-15
SLIDE 15

A Request from the Lecturer

§ If anything is unclear, you are curious about something, etc.

  • Please ask a question
  • This makes the lecture livelier and more interesting (for all including me)

§ If you find mistakes on the slides

  • Please point them out; if you are unsure, by email or direct message
  • Improves the quality of the lecture

§ I will compare with other programming languages

  • Comparisons not in the slides are not required for the exam
  • Of course, I will stress the advantages of C++ (this is a C++ lecture)
  • Yes, C++ has its downsides, they will be addressed as well
  • Any language can be used to write good and bad programs
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

15

slide-16
SLIDE 16

Q & A?

§ Course material?

  • Slides
  • Lectures will be recorded and made available

§ Books?

  • Bjarne Stroustrup. The C++ Programming Language (3rd Ed.). Addison-

Wesley.

  • Stanley B. Lippman, Josée Lajoie, Barbara E. Moo. C++ Primer (5th Ed.).

Addison-Wesley.

  • Scott Meyers. Effective C++: 55 Specific Ways to Improve Your Programs and

Designs Addison-Wesley

  • Bjarne Stroustrup. A Tour of C++ (2nd Ed.). Addison-Wesley.
  • There are newer ones too; check out your local bookstore!

§ Which operating system/C++ compiler?

  • Any (Mac: xcode; Windows: Cygwin; Linux: cli tools)
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

16

slide-17
SLIDE 17

Advanced Software Engineering with C++ Templates

Namespaces, Classes, User-Defined Types

Thomas Gschwind <thgatzurichdotibmdotcom>

slide-18
SLIDE 18

Classes, User-Defined Types

§ Motivation

  • Encapsulation
  • When and why?

§ Declaration & Definition § Constructors § Destructors § References § Operators § Constant Classes § User-defined conversions § constness

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

18

slide-19
SLIDE 19

Classes

§ Encapsulation

  • Add structure to the program
  • Gives class an explicit interface (access to class checked by compiler)
  • User only needs to know this interface
  • Hide implementation details

§ Abstract data types (e.g., stack, vector, map, …) § User-defined types

  • Allows developers to develop types that mimic primitive types

(such as a fraction or complex number data type): fraction x(4,3), y(2); fraction z = x*x + y;

  • One of the key differences between

C++ and C (or Java)

Decide which types you want; provide a full set of operations for each type. Bjarne Stroustrup

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

19

slide-20
SLIDE 20

Classes: When are They Needed?

§ Non OO languages such as C do not provide classes but only structures or records

  • Classes simulated with functions

taking the same record (typically) as first argument

§ Classes are useful for

  • User defined types
  • Abstract data types

(e.g., vector, map, …)

  • Whenever you have many

functions that operate on the same data

typedef struct { int s[256]; int sp; } Stack; void stack_init(Stack *s) { s->sp=256; } void stack_push(Stack *s, int i) { s->s[--s->sp]=i; } int stack_pop(Stack *s) { return s->s[s->sp++]; } int stack_empty(Stack *s) { return s->sp==256; } void main(int argc, char *argv[]) { Stack s; stack_init(&s); // use s }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

20

slide-21
SLIDE 21

Classes: Declaration & Definition

§ A new type is defined with struct or class (or typedef as in C) § Members may be defined inside the class definition

  • Implicitly defined as

“inline” members

  • Useful for small functions

§ Members may be defined

  • utside the class

definition

  • Prepend name with

classname::

struct fraction { // declaration+definition int c, d; // counter and denominator fraction(int cntr = 0, int denom = 1) : c(cntr), d(denom) { /*void*/ } int get_counter(void); void set_counter(int counter); };

fraction.h

int fraction::get_counter(void) { return c; } void fraction::set_counter(int cntr) { c = cntr; // or this->c = cntr; }

fraction.cc default parameters default parameters

this is a pointer and is accessed with ->

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

21

slide-22
SLIDE 22

Classes: Implementation

§ When the compiler compiles our class, it

  • converts member functions to individual functions, and
  • adds the implicit this parameter to each function

§ Just using member functions adds no overhead to your program!

struct fraction { int c, d;

fraction(int cntr, int denom=1) : c(cntr), d(denom) { /*void*/ }

int get_counter(void) { return c; } void set_counter(int cntr); }; void fraction::set_c…(int cntr) { c = cntr; }

“External” View

struct fraction { int c, d; }; void fraction_init(fraction *this) { this->c = cntr; this->d = denom; } int get_counter(fraction *this) { return this->c; } void set_counter(fraction *this, int cntr) { this->c = cntr; }

Simplified “Internal” View

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

22

slide-23
SLIDE 23

template <class T> inline void swap(T &a, T &b) { T c(a); a=b; b=c; } template <class T> T gcf(T a, T b) { if (a<b) { swap(a, b); } while (b!=0) { a=a-b; if (a<b) { swap(a, b); } } return a; } // T c(a); a=b; b=c; // T c(a); a=b; b=c;

Sidebar: inline

§ Replaces function call with function’s body

  • inline functions go into header file
  • Code needs to be known during

compile time

§ When to use it?

  • Useful for small functions
  • Sometimes also for larger ones

§ Faster and more compact code § For C Developers: Combines advantages of macros and functions

  • Own scope for parameters and variables
  • No side effects
  • As efficient as macros (if possible)
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

23

slide-24
SLIDE 24

Classes: Constructor & Destructor

§ Constructor (T)

  • Executed after memory allocated for an object
  • The “:” section
  • Initialize members by skipping their default construction
  • Since C++11, invoke other constructors from the same class using T(…)

§ Destructor (~T)

  • Executed before memory will be deallocated for an object
  • Similar but better than Java‘s finalize() method

(because the time it is executed is well known)

  • Allows you to free additional resources (we will come back to this)

class Fraction { public: Fraction(...) : ... { // … } // Constructor ~Fraction(void) { // … } // Destructor };

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

24

slide-25
SLIDE 25

Classes: Encapsulation, Access Control

§ public:

  • Members declared in this section may be used by anybody

(default for structures)

§ private:

  • Things declared here may only be used by this class
  • Useful for helper methods and attributes (default for classes)

§ protected:

  • Things declared here may only be used by this class and its subclasses

(We will discuss inheritance in a future lecture)

§ friend …

  • Allow a given artifact to access the internals of a class
  • Although different, frequently compared to package in Java
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

25

slide-26
SLIDE 26

Classes: That‘s what Friends are for …

§ Allow other functions and classes access to protected and private members § Useful for

  • Functions, operators, etc. that logically belong to a class but cannot be

defined as member thereof such as:

  • Classes having a close relationship with each other

class fraction { friend int read(fraction &f); friend int write(fraction f); … }; class my_matrix { friend class my_vector; … };

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

26

slide-27
SLIDE 27

Difference struct vs. class: Visibility

§ Both mean and do the same § Except members of structs are by default public whereas members of classes are by default private § The following is the same

  • Typically class is used in C++
  • structs are typically used for structures whose members are all public

struct fraction { private: … } class fraction { … }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

27

slide-28
SLIDE 28

Classes: …

§ Now, let us put together what we have discussed so far …

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

28

slide-29
SLIDE 29

User-Defined Fraction Type in Java and C++

class Fraction { // type definition private int cntr; private int denom; public Fraction(int c, int d) { cntr=c; denom=d; } public int getCounter() { return cntr; } public void setCounter(int c) { cntr=c; } public int getDenominator() { return denom; } … } class fraction { // type definition int cntr; int denom; public: fraction(int c=0, int d=1) : cntr(c), denom(d) { /*void*/ } int get_counter(void) { return cntr; } void set_counter(int c) { cntr=c; } int get_denominator(void) { return denom; } … };

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

29

slide-30
SLIDE 30

Using the Fraction Data Type

§ In Java

void main(String[] args) { Fraction f=new Fraction(Integer.parseInt(args[1]), Integer.parseInt(args[2])); System.out.println(f.getCounter()+":"+f.getDenominator()); } void main(int argc, char *argv[]) { fraction f(atoi(argv[1]), atoi(argv[2])); cout << f.get_counter() << ":" << f.get_denominator() << endl; }

§ In C++

allocated on the heap allocated on the stack deallocated by Java during next garbage collector run deallocated by C++ when scope is left

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

30

slide-31
SLIDE 31

Sidebar: Memory “Management” in C++

§ In Java

  • Built-in types are stored on the stack
  • Objects are stored on the heap

(references to objects are stored on the stack)

  • Only references to objects
  • Memory is automatically freed by the garbage collector

§ In C++

  • Built-in types and objects both can be stored on the stack and the heap
  • C++ supports references (T&) and pointers (T*):

both can refer/point to objects and built-in types

  • Data on the stack automatically deallocated when the scope is left
  • Data on the heap must be deallocated by the user

§ More details (including move constructor) in the next lecture

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

31

slide-32
SLIDE 32

Calculating with Fractions

§ We would like to do calculations with our fraction type § How do we define arithmetic operations such as +, -, …? § How can these operations be invoked?

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

32

slide-33
SLIDE 33

Operators(?) in Java

§ In Java, we simply define methods mul and div to do the computation § They could be named anything and are used like any other method

class Fraction { // type definition private int c; private int d; public Fraction(int cntr, int denom) { c=cntr; d=denom; } public Fraction mul(Fraction b) { int f1=gcf(this.c, b.d), f2=gcf(b.c, this.d); return new Fraction((this.c/f1)*(b.c/f2), (this.d/f2)*(b.d/f1)); } public Fraction div(Fraction b) { return mul(new Fraction(b.d, b.c)); } }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

34

slide-34
SLIDE 34

User-Defined Operators

§ C++ supports user-defined operators § Operators are “normal” functions with a “special” name such as

  • perator+, operator-, …

§ When you use the operator, the compiler automatically invokes the corresponding function

fraction operator*(fraction a, fraction b) { int f1=gcf(a.get_c…(), b.get_d…()), f2=gcf(b.get_c…(), a.get_d…()); return fraction((a.get_counter()/f1) * (b.get_counter()/f2), (a.get_denominator()/f2) * (b.get_denominator()/f1)); } fraction operator/(fraction a, fraction b) { return a * fraction(b.get_denominator(), b.get_counter()); }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

35

slide-35
SLIDE 35

fraction f(1, 2); fraction g(3); fraction h = f*g; fraction i = (h+g*h)*h; // if you truly prefer, the following works too // fraction h2 = operator*(f, g);

User-Defined Operators

§ Operator invocation

  • C++ takes the standard operator precedence into account
  • i.e., a+b*c will be interpreted as operator+(a, operator*(b, c))
  • operator+(a, b) if you truly prefer
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

36

Fraction f = new Fraction(1, 2); Fraction g = new Fraction(3, 1); Fraction h = f.mul(g); Fraction i = h.add(g.mul(h)).mul(h);

slide-36
SLIDE 36

User-Defined Operators (cont‘d)

§ Operators may also be defined as member functions § There is no difference during their invocation § The left operand implicitly becomes the “this” argument § Visibility? Yes, we may access private members of another instance of the same type

class fraction { // type definition int c; int d; public: fraction(int cntr=0, int denom=1) : c(cntr), d(denom) { /*void*/ } fraction operator*(fraction b) { int f1=gcf(c, b.d), f2=gcf(b.c, d); return fraction((c/f1) * (b.c/f2), (d/f2) * (b.d/f1)); } fraction operator/(fraction b) { swap(b.c, b.d); return (*this) * b; } } Visibility?

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

37

slide-37
SLIDE 37

User-Defined Operators: Guidelines

§ Adhere to mathematical properties

  • foo==foo

Reflexivity

  • foo==bar Û bar==foo

Symetry

  • foo==bar Ù bar==foobar Þ foo==foobar

Transitivity

§ Consider mathematical laws

  • (a+b)+c == a+(b+c)

Associativity

  • a*b == b*a

Commutativity

§ Consider typically equivalent operations

  • foo+=bar Û foo=foo+bar
  • foo!=bar Û !(foo==bar)
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

38

slide-38
SLIDE 38

Classes: Default Artifacts

§ Created by the compiler, if not defined § Default Constructor (T(void))

  • Initializes each attributes with default constructor

§ Copy Constructor (T(const T&))

  • Copies each attribute with copy constructor (potentially, a “shallow copy“)
  • May be executed when T is passed or returned by value
  • C++ tries to avoid unnecessary copies through

copy elision and return value optimization strategies

§ Assignment Operator (operator=(T))

  • Copies each attribute with operator= (potentially, a “shallow copy”)

§ Destructor

  • Does nothing
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

39

“&”?!? Don’t copy the

  • parameter. The

function wants to work

  • n the caller’s instance
  • f the parameter.
slide-39
SLIDE 39

Classes: Disable Default Artifacts

§ If we do not want the default artifacts, we can block their creation

  • Useful if for instance an object should not ever be duplicated by „accident“

§ Hide the default constructor

  • Declare in the private part of the class
  • The class itself may still use those artifact

§ If the class itself should not be allowed to use it

  • Since C++11, declare the artifact with “= delete”

(T(const T&) = delete)

  • Prior to C++11, declare it in the class but never implement it

=> Compiler won‘t create it => Linker will complain if it is ever used

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

40

slide-40
SLIDE 40

Classes: Rule of Three

§ The “Rule of Three” states that if you implement either of the following three, you most likely need all three of them

  • Copy Constructor
  • Assignment Operator
  • Destructor

§ Hence, it is good practice to implement all of these, even if you truly do not need the other artifacts

  • Just provide the same code that the compiler would have generated
  • This shows that you did not forget about them and this is your intent
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

41

slide-41
SLIDE 41

Classes: Alternatively, always Implement Default Artifacts?

§ As alternative to “The Rule of Three”, some developer suggest to always provide all default artifacts § This is overly verbose but possibly a matter of taste

class fraction { // type declaration+definition int c; int d; public: fraction(int cntr=0, int denom=1) : c(cntr), d(denom) { /*void*/ } // redundant fraction(const fraction &f) : c(f.c), d(f.d) { /*void*/ } ~fraction(void) { /*void*/ } fraction &operator=(fraction b) { c = b.c; d = b.d; return *this; } … };

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

42

Same as the compiler-generated one and it intentionally contains no code (/*void*/) Same as the compiler-generated one Same as the compiler-generated one and it intentionally contains no code (/*void*/)

slide-42
SLIDE 42

Classes: User-Defined Conversion Operations

§ C++ allows users to define implicit conversion functions § If, e.g., we want to pass a fraction to a function expecting a double

class fraction { public: … // declare and define implicit conversion fraction to double

  • perator double() { return (double)c/d; }

}; double solve(double p, double q) { // solve x^2+px+q=0 return -p/2+sqrt(p*p/4-q); } void foo(fraction &a, fraction &b) { cout << "The result is " << solve(a, b) << endl; // implicit cout << "a+b=" << (double)(a+b) << endl; // explicit }

Should invoke a user-defined conversion Style-wise, in C++, one should use static_cast<double>(a+b)

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

43

slide-43
SLIDE 43

C++/C const vs. Java final

§ C++/C const specifies that a given variable or object a variable points to is constant § Java final specifies that the value of a variable cannot be changed

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

44

slide-44
SLIDE 44

C/C++ const vs Java final

C++ Java

const int a=17; vector<string> v1; v1.push_back("Hello"); const vector<string> v2; v2.push_back("Hello"); const vector<string> *vp=&v2; vp=&v1; Vp->bush_back("Hello"); vector<string> *const vq=&v2; vq=&v1; vq.bush_back("Hello"); vector<string> *vr=&v2; final int a=17; Vector v1=new Vector(); v1.add("Hello"); final Vector v2=new Vector(); v2.add("Hello"); final Vector vp=v2; vp=v1; vp.add("Hello"); Vector vr=v2;

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

45

L1 L2 L3 L4 L5 L6 L7 L8 L9 La Lb Lc

slide-45
SLIDE 45

C/C++ const vs Java final

C++

C++ (C) distinguish whether the pointer is const or the structure pointed to

Java

Java uses an overly simplistic model that only worries about the reference

const int a=17; vector<string> v1; v1.push_back("Hello"); const vector<string> v2; v2.push_back("Hello"); const vector<string> *vp=&v2; vp=&v1; vp.push_back("Hello"); vector<string> *const vq=&v2; vq=&v1; vq.push_back("Hello"); vector<string> *vr=&v2; final int a=17; Vector v1=new Vector(); v1.add("Hello"); final Vector v2=new Vector(); v2.add("Hello"); final Vector vp=v2; vp=v1; vp.add("Hello"); Vector vr=v2; OK OK OK OK ====================== OK OK ====================== ============================= ======= OK ======================= OK OK OK OK OK OK ====== OK OK

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

46

slide-46
SLIDE 46

C/C++ const (cont’d)

§ v2.push_back is NOT OK § BUT v2.size is OK? § How can the compiler tell the difference? § The secret is the declaration of the member…

const vector<string> v2; v2.push_back("Hello"); int i=v2.size(); OK ====================== OK … class vector { public: void push_back(T elem); int size() const; }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

47

slide-47
SLIDE 47

Namespaces

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

48

§ Definition § Importing § Operator Overloading Resolution

slide-48
SLIDE 48

Namespaces

§ Modular programming § Avoid name collisions § User defined data-types

namespace fractions { // … int gcf(int a, int b); int lcm(int a, int b); int swap(int &a, int &b); // … } Namespace declarations need to be repeated again in the corresponding .cc file

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

49

slide-49
SLIDE 49

Namespaces (cont’d)

§ Namespaces may be anonymous

  • namespace /* no name given */ { … }

§ A source file may contain

  • Multiple namespace statements
  • Nested namespace statements

namespace util { int gcf(int a, int b); int lcm(int a, int b); int swap(int &a, int &b); } namespace fractions { class fraction { … }; } } namespace util2 { … }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

50

// C++17 also supports :: for // nested namespaces namespace util { int gcf(int a, int b); … } namespace util::fractions { class fraction { … }; } …

slide-50
SLIDE 50

Using Namespaces

§ Scoping

  • :: Operator
  • Example: util::gcf(foo,bar);

§ Import a single name of a given namespace

  • using declaration
  • Example: using NAMESPACE::VAR;

§ Import all names defined in a given namespace

  • using directive
  • Example: using namespace NAMESPACE;

§ Examples on all slides assume that namespace std was imported using namespace std;

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

51

slide-51
SLIDE 51

Multiple operators?

§ Operators can be defined in multiple ways and scopes

  • As member function:

fraction fraction::operator+(complex b);

  • Stand-alone:

fraction operator+(fraction a, complex b);

  • As stand-alone operator, in the current namespace, or that of fraction, or

that of complex

§ BUT which one will be used by the compiler?

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

52

slide-52
SLIDE 52

Multiple operators? (cont’d)

Example Solution 1. Does A have a member operator+(b) => yes => use it, if it has multiple, use standard overloading rules 2. Is there an operator+(a,b) defined in the namespace where A or B is defined in (in that order)? => yes => use it, if it has multiple, use standard overloading rules

fraction a; complex b; cout << a+b << endl; A a; B b; cout << a+b << endl;

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

53

slide-53
SLIDE 53

Advanced Software Engineering with C++ Templates

Standard Library – Basics

Thomas Gschwind <thgatzurichdotibmdotcom>

slide-54
SLIDE 54

The Standard Library

§ Basic Input & Output § Strings § Containers § Iterators § A good overview of the classes and its API can be found here: http://www.cppreference.com/

No significant program is written in just a bare programming language. Bjarne Stroustrup

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

55

slide-55
SLIDE 55

Input and Output: Basics

§ The C++ Standard Library uses

  • cin to denote standard input, and
  • cout to denote standard output

§ C++ uses operators for reading and writing data types

  • To write it to an output stream: operator<<
  • To read it from an input stream: operator>>

cout << "What is your name? "; cin >> name; cout << "Hello " << name << endl; First operand, the output (input) stream Returns the output stream itself, to support chaining of operators Second operand, the value to write (read)

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

56

slide-56
SLIDE 56

Input and Output: More Streams and Functions

§ File streams <fstream>

  • ifstream, ofstream, fstream

§ String streams <sstream>

  • istringstream, ostringstream, stringstream

§ More input and output functions

  • get, getline, ignore, read, gcount
  • write
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

57

slide-57
SLIDE 57

Input and Output: Samples

int main(int argc, char *argv[]) { char first[256], mi, street[256]; string last, city; // read a word terminated by whitespace cout << "First Name? "; cin >> first; // suspect cout << "Middle Initial? "; cin >> mi; // ok cout << "Last Name? "; cin >> last; // ok // read a line terminated by newline cin.ignore(256, '\n'); // ok cout << "Address? "; cin.get(street, 256); // suspect cout << "City? "; getline(cin,city, '\n'); // ok cout << "Hello, " << first << "!" << endl; cout << "I like " << city << "!" << endl; }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

58

slide-58
SLIDE 58

Input and Output: Stream States

§ This program reads a character § Checks the stream’s state

  • good: all is fine
  • fail: last operation failed
  • bad: characters may have been lost
  • eof: reached end-of-file

§ If the stream state is good continue, otherwise terminate § Confert LF to CR,LF and continue with the next character

#include <iostream> #include <fstream> int main(int argc, char *argv[]) { ifstream ifs(argv[1]);

  • fstream ofs(argv[2]);

char c; for (;;) { ifs >> c; if (!ifs.good()) break; if (c=='\n') ofs << "\r\n"; else ofs << c; } }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

59

slide-59
SLIDE 59

“Unix” to “DOS” Text Converter

§ This program should have converted a text file from “Unix” LF to “DOS” CR,LF newline convention § The program exhibits a common

  • versight

§ In the output file, all space are missing § operator>> by default skips whitespaces § Typically, this is what is wanted

#include <iostream> #include <fstream> int main(int argc, char *argv[]) { ifstream ifs(argv[1]);

  • fstream ofs(argv[2]);

char c; for (;;) { ifs >> c; if (!ifs.good()) break; if (c=='\n') ofs << "\r\n"; else ofs << c; } }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

60

slide-60
SLIDE 60

Unix to DOS Converter II

§ The istream::get() member functions reads the next character without skipping whitespaces

#include <iostream> #include <fstream> int main(int argc, char *argv[]) { ifstream ifs(argv[1]);

  • fstream ofs(argv[2]);

char c; for (;;) { ifs.get(c); if (!ifs.good()) break; if (c=='\n') ofs << "\r\n"; else ofs << c; } }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

61

slide-61
SLIDE 61

Input and Output: Classes

§ Operators must be defined stand-alone OR as part of the left operand’s type

  • Cannot extend the output (or input) stream whenever a new type is added
  • Stand-alone operators cannot access the class’s private data
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

62

cout << "What is your name? "; cin >> name; cout << "Hello " << name << endl; Return type, the output stream, to support chaining

by default

First operand, the output (input) stream Second operand, the value to write (read) Putting it together, gives:

  • stream &operator<<(ostream &os, T x);
slide-62
SLIDE 62

Input and Output: Classes (cont’d)

§ Remember: Functions declared as friend may access a class’s protected and private members

  • Functions, operators, etc. that logically belong to a class but cannot be

defined as member thereof such as input and output routines

class fraction { friend istream &operator>>(istream &is, fraction &f); friend ostream &operator<<(ostream &os, fraction f); … };

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

63

slide-63
SLIDE 63

Input and Output: Classes (cont’d)

§ Now, we can access the private members

(In this case using {get,set}_{counter,denominator} would have been equally performant and at least equally readable)

§ operator>> should only change the 2nd parameter if the read is successful

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

64

  • stream &operator<<(ostream &os, fraction f) {
  • s << '(' << f.c << '/' << f.d << ')';

return os; } void check_char(istream &is, char ch) { char c; is >> c; if(c!=ch) { is.putback(c); is.setstate(ios::badbit); } } istream &operator>>(istream &is, fraction &f) { fraction g; check_char('('); is >> g.c; check_char('/'); is >> g.d; check_char(')'); if(is) f=g; return is; }

Remember the stream states: good: stream is good fail: last operation failed bad: characters may have been lost eof: reached end-of-file

slide-64
SLIDE 64

String Functions

§ s1.append(s2) Append s2 to s1 § s1.insert(pos, it1, it2) Insert sequence from it1 to it2 in string s1 at pos § s1.replace(idx, len, s2) Replace len characters in s1 starting from idx with s2 § getline(is, s) Read a line from input stream is into string s

#include <string> … int main(int argc, char *argv[]) { string h("Hello"), w("World"), s; w.append("!"); cout << w[5] << w.at(5) << endl; w.insert(w.begin(), h.rbegin(), h.rend()); cout << w << endl; w.replace(4,2,"H W"); cout << w << endl; cout << "Enter your name: "; getline(cin, s); cout << h << " " << s << endl; return 0; }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

65

slide-65
SLIDE 65

Container

§ Provide different data structures § Abstraction of a memory area § User-defined allocators § Can be accessed using iterators

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

66

slide-66
SLIDE 66

Containers (Overview)

§ Sequence Containers

  • vector<T>, list<T>, forward_list<T>, deque<T>

§ Associative Containers

  • map<K,V>, multimap<K,V>
  • set<K>, multiset<K>
  • unordered_map<K,V>, unordered_multimap<K,V>
  • unordered_set<K>, unordered_multiset<K>

§ Sequence Container Adapters

  • stack<T,C>
  • queue<T,C>, priority_queue<T,C>
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

67

slide-67
SLIDE 67

A Simple vector Example

#include <iostream> #include <string> #include <vector> using namespace std; int main(int argc, char *argv[]) { vector<string> playlist; playlist.push_back("1. Have A Nice Day"); playlist.push_back("2. Crocodile Rock"); playlist.push_back("3. Welcome To Wherever You Are"); playlist.push_back("4. Who Says You Can't Go Home"); playlist.push_back("5. Last Man Standing"); ...

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

68

slide-68
SLIDE 68

string O(1) O(n)+ O(n)+ O(n) Insert/Remove Elements

Complexity Guarantees

Begin Middle End vector deque list map, set O(n)+ O(1)+ O(1) O(n) O(1) O(1) O(1) O(1) O(log(n))+ [ ] O(1) O(1) O(log(n)) Ran Iterator Ran Ran Bi

forward_list

O(1) O(1) For Bi

unordered_map, unordered_set

O(1)+ O(1)+ For

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

71

slide-69
SLIDE 69

Iterators

§ Define a sequence over the elements in a container

Iterator2: { T* start; int pos; } vector: T*

#1 #2 #3 #4 #5 #6 #7 … #n #8 #9 #0

Iterator1: T *p

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

72

slide-70
SLIDE 70

More on Iterators (cont‘d)

List: lnk*

lnk lnk lnk lnk lnk … #0 #1 #2 #3 #4

Iterator3: lnk *p

nd nd nd nd nd nd nd

Map: Iterator4: ndi p

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

73

slide-71
SLIDE 71

Java Trivia

... // store playlist in ArrayList playlist BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ListIterator i = playlist.listIterator(); String song = "none"; for (;;) { System.out.println("playing "+song); String cmd = in.readLine(); if (cmd.equals("quit")) break; if (cmd.equals("next") && i.hasNext()) { song = (String)i.next(); } else if (cmd.equals("prev") && i.hasPrevious()) { song = (String)i.previous(); } else { System.out.println("unknown command "+cmd); } }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

74

slide-72
SLIDE 72

Java Trivia

... // store playlist in ArrayList playlist BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ListIterator i = playlist.listIterator(); String song = "none"; for (;;) { System.out.println("playing "+song); String cmd = in.readLine(); if (cmd.equals("quit")) break; if (cmd.equals("next") && i.hasNext()) { song = (String)i.next(); } else if (cmd.equals("prev") && i.hasPrevious()) { song = (String)i.previous(); } else { System.out.println("unknown command "+cmd); } }

Constantly going back and forth in the playlist will repeatedly play the same song

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

75

slide-73
SLIDE 73

Iterators the C++ Way

vector<string> playlist; ... // store playlist in ArrayList playlist vector<string>::iterator fst = playlist.begin(), cur = fst, lst = playlist.end(); string cmd; for (;;) { if (cur == lst) cout << "playing none" << endl; else cout << "playing " << *cur << endl; cin >> cmd; if (cmd == "quit") break; if (cmd == "next" && cur != lst) ++cur; else if (cmd == "prev" && cur != fst) --cur; else cout << "unknown command " << cmd << endl; }

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

76

In C++11, also:

auto fst = begin(pl…st), cur = fst, lst = end(playlist);

slide-74
SLIDE 74

Different Types of Iterators

Iteration

++ ++ ++ ++ --

input forward bi- directional Abbrev. Access Read Write In For Bi

  • >
  • >
  • >

=*p =*p =*p *p= *p=

  • utput

Out

*p=

Category random- access Ran

=*p

  • > []

*p= ++ + +=

  • - - -=

Compare

== != == != == != == < <= != > >=

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

77

slide-75
SLIDE 75

Iterators (Java vs. C++)

Java § Iterator obtained using iterator(), a ListIterator using listIterator() § Iterator points between elements => current element cannot be accessed multiple times § Iterator knows about first and last position => inflexible since routines cannot be easily changed to iterate over a part of the container § If bounds are exceeded, an exception is raised C++ § Iterator returned through begin() and end() or rbegin() and rend() § Iterator points to the element => current element can be returned multiple times § Iterator does not know about begin and end; second iterator is used for this purpose => flexibility as side effect; routine can iterate over any segment of the container § If bounds are exceeded, undefined behavior, probably a “segmentation violation”

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

78

slide-76
SLIDE 76

Iterators (Java vs. C++)

C++ § Iterator points to the elements (green) § Repeatedly going forward and backward gives alternating elements

Java § Iterator points between the elements (red) § Repeatedly going forward and backward gives the same element vector:

#1 #2 #3 #4 #5 #6 #7 … #n #8 #9 #0

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

79

slide-77
SLIDE 77

Summary

§ Administrative Issues § Classes § Namespaces § Standard Library

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

80

slide-78
SLIDE 78

Exercise L1.1

§ Implement a program that displays Hello World § Implement a program that converts Unix style text files to MSDOS style text files and vice-versa

  • Unix uses ‘\n’ as line separators
  • MSDOS uses ‘\r’ followed by ‘\n’ as line separators
  • How do you deal with incorrectly formatted Unix text files?

§ Note: You should also be able to explain the C++ concepts used

  • For example what does << mean
  • What are the arguments expected
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

81

slide-79
SLIDE 79

Exercise L1.2 (this code will be reused in a future exercises)

§ Implement the fraction type

  • Implement the +, -, *, / operators
  • Implement the << and >> operators
  • Provide two test drivers
  • One that checks based on a few samples that your code is correct
  • One that lets a user invoke some operations with fraction numbers

(either interactively or through command line options)

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

82

slide-80
SLIDE 80

Exercise L1.3 (this example will be extended in future exercises)

Simple Spell Checker § Implement a simple spell checker. The spell checker takes two files as command line arguments, a dictionary file containing a list of correctly spelled words and a file whose content is to be checked. Upon startup, your program stores the words contained in the dictionary file in a set<string>. Then it reads every word in the file to spell check, checks whether each word is correctly spelled (ie contained in the dictionary file) and if not displays it on cout.

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

83

slide-81
SLIDE 81

Exercise L1.3 – An Example

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

84

correctly spelled words are stored in the dictionary

dict.txt

a comprehensive dictionary is important.

text.txt

prompt$ check dict.txt text.txt a comprehensive is important prompt$

slide-82
SLIDE 82

Exercise L1.4 (this example will be extended in future exercises)

§ Implement an RPN (Reverse Polish Notation Calculator)

  • When the user enters ‘q’ the program terminates
  • When the user enters ‘n’ followed by a number, it is put on the stack
  • When the user enters ‘d’ the last number is removed from the stack
  • When the user enters ‘+’, ‘-’, ‘*’, ‘/’, the calculator takes the last two numbers

from the stack applies the operation to the numbers and puts the result on the stack

  • When the user enters ‘min’, the calculator takes the last two numbers from

the stack applies the operation to the numbers and puts the minimum of the two numbers back onto the stack

  • Use the std::vector container and its iterator

§ Hint

  • If you want to use the min function from this lecture, you may want to

rename it to mymin to avoid confusion with std::min

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

86

slide-83
SLIDE 83

Exercise L1.4: An Example (user input in bold)

Command: n 2 n 4 n 3 1: 2 2: 4 3: 3 Command: * 1: 2 2: 12 Command: - 1: -10 Command: n 2 / 1: -5 Command: d Command: q

Notes:

  • Don’t worry if your UI is

slightly different.

  • Extra-points if you use a

getline for reading the commands and an istringstream for parsing the commands and arguments.

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

87

slide-84
SLIDE 84

Exercise L1.5

§ Which functions cannot be inlined? Implement a program that shows such a function. § Verify your claim by looking at the compiler-generated assembly code (no need to understand all the assembly code, only whether your function was inlined or not) § Useful compiler options

  • -O0 asks the compiler to not optimize the output

(compiler probably does not inline functions (by itself))

  • -O3 asks the compiler to apply almost all optimizations

(compiler likely will inline functions not marked as such)

  • -S asks the compiler to generate assembly code only
  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

88

slide-85
SLIDE 85

Next Lecture

§ Templates § Separate Compilation § Memory Management Happy Coding and See You in Two Weeks…

  • Th. Gschwind. Advanced Software Engineering with C++ Templates.

89