Challenges of This Course. Object-oriented Programming in C++ Outline of Day 1. What Will be Covered in This Course. Outline of Day 2 & 3

Similar documents
Object-oriented Programming in C++

Object-oriented Programming in C++

Object-oriented Programming in C++

6. Pointers, Structs, and Arrays. 1. Juli 2011

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Part V. Object-oriented Programming. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

4. Functions. March 10, 2010

5. Applicative Programming. 1. Juli 2011

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

10. Object-oriented Programming. 7. Juli 2011

Fast Introduction to Object Oriented Programming and C++

Absolute C++ Walter Savitch

8. Object-oriented Programming. June 15, 2010

CE221 Programming in C++ Part 1 Introduction

Problem Solving with C++

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Introduction to Programming using C++

III. Classes (Chap. 3)

Cpt S 122 Data Structures. Introduction to C++ Part II

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Object-Oriented Programming for Scientific Computing

CS201 Latest Solved MCQs

PIC 10A Objects/Classes

Operator overloading

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Come and join us at WebLyceum

CS3157: Advanced Programming. Outline

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Polymorphism Part 1 1

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

G52CPP C++ Programming Lecture 9

Lecture 10: building large projects, beginning C++, C++ and structs

377 Student Guide to C++

CS201 Some Important Definitions

Chapter 1 Getting Started

AN OVERVIEW OF C++ 1

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Instantiation of Template class

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Lecture 14: more class, C++ streams

Chapter 2: Basic Elements of C++

Object Oriented Software Design II

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CSCI 171 Chapter Outlines

Lecture 13: more class, C++ memory management

Lecture 7. Log into Linux New documents posted to course webpage

Interview Questions of C++

Object-Oriented Programming

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

A brief introduction to C++

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

EL6483: Brief Overview of C Programming Language

CS2141 Software Development using C/C++ C++ Basics

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Reliable C++ development - session 1: From C to C++ (and some C++ features)

CS 376b Computer Vision

CS

For Teacher's Use Only Q No Total Q No Q No

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

QUIZ. What is wrong with this code that uses default arguments?

Pointers and References

G52CPP C++ Programming Lecture 20

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

COEN244: Class & function templates

C++ (Non for C Programmer) (BT307) 40 Hours

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Engineering Tools III: OOP in C++

Software Design and Analysis for Engineers

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Software Engineering /48

CS304 Object Oriented Programming Final Term

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

CS 231 Data Structures and Algorithms, Fall 2016

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Scientific Computing

CPSC 427: Object-Oriented Programming

PHY4321 Summary Notes

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Lecture 2, September 4

CS24 Week 3 Lecture 1

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

2 ADT Programming User-defined abstract data types

What are the characteristics of Object Oriented programming language?

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

CPSC 427: Object-Oriented Programming

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Objectives. In this chapter, you will:

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Object-Oriented Design (OOD) and C++

Chapter 15 - C++ As A "Better C"

Transcription:

Challenges of This Course Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel June 30, 2014 Heterogeneity of the audience (different level of programming experience, different programming languages, etc.); We assume: Experience in procedural programming (FORTRAN, C, or similar) availability of a notebook with some C++ compiler (Details on installation for win in Tutorial 1) Variety of topics related to C++ selection of topics! General: Giving a lecture on how to swim won t work participants have to jump into water (i.e. program!) Restricted amount of time long-term learning effects not without using C++ for different tasks yourself! Working with C and C++, June 30, 2014 1 Working with C and C++, June 30, 2014 2... What Will be Covered in This Course Working with C and C++, June 30, 2014 3 Basic usage From text files to binary code header files vs. implementation files C ++ as an increment of C Basics of C memory management: data types, pointers, control structures (loops/if/switch) functions call by value vs. reference... From C to C ++ (Extensions) namespaces references... Outline of Day 1 Working with C and C++, June 30, 2014 4 Outline of Day 2 & 3 Outline of Day 4 Object-oriented Programming s/way of thinking Syntax in C++ Inheritance (taxonomy) Information hiding OO Continued Polymorphism Overloading, deep vs. shallow copy Type conversion, explicit (temporary objects) Usage of const File I/O Templates & the Standard Template Library STL Understanding templates (templated function, templated class) The Standard Template Library Using templates and STL for data structures (containers) and algorithms Working with C and C++, June 30, 2014 5 Working with C and C++, June 30, 2014 6 What Will NOT be Covered in This Course... Organisation of This Course... and is nevertheless interesting/relevant: exception handling assertions details on libraries (static vs. shared) details on design patterns preprocessor commands and macros makefiles & Co. automatic testing (cppunit etc.) automatic code documentation (doxygen, doxys, etc.) debugging with gdb, valgrind & Co. Persons: Day 1+2: Tobias Neckel Day 3+4: Wolfgang Eckhardt Times: 4 days: 2h lecture + 2h tutorials each Website: General infos: http://www5.in.tum.de/wiki/index.php/ Object-oriented_Programming_wC%2B%2B_GRS-_2014 Examples used on the slides: http://www5.in.tum.de/ lehre/vorlesungen/progcourse/c++/grs_2014/src/ Working with C and C++, June 30, 2014 7 Working with C and C++, June 30, 2014 8

1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Functions en detail Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Backup Working with C and C++, June 30, 2014 9 1 Basic Usage Working with C and C++, June 30, 2014 10 1.1 From Text Files to Binary Code Comments in C / C ++ 1 // one line comment as in FORTRAN, source code needs to be compiled: 3 /* 4 several lines 5 */ source: http://pages.towson.edu/davani/cosc236/handouts/com-process.html 7 /** 8 * several lines, autodocutool syntax : 9 * 10 * This file is part of the C++ course. 11 * @author Tobias Neckel, Wolfgang Eckhardt 12 * 13 * @section LICENSE 14 * Copyright (c) 2014 15 * 16 * @section DESCRIPTION 17 * Simple example showing pointer aspects 18 * 19 * compile : g++ -O3 -g array. cpp -o array 20 **/ Working with C and C++, June 30, 2014 11 Working with C and C++, June 30, 2014 12 A First Example Basic Compilation 13 # include <iostream > 14 15 int main () { 16 std :: cout << "printing output... " << std :: endl ; 17 std :: cout << "first computation : 5+11= " << 5+11 << std :: endl ; 18 return 0; 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basic_usage/first_example.cpp C / C ++ comes along with lots of useful standard libraries. Libraries provide a lot of useful operations. Examples: iostream math.h Add declarations via include statements ( compiler knows declarations). For (external) libraries in different path: use -I path/to/lib/includes to inlcude 1 g++ -O3 -g first_example. cpp -o test_executable Working with C and C++, June 30, 2014 13 Working with C and C++, June 30, 2014 14 1.2 Header Files A Second Example: More Than One File 13 # include <iostream > 14 # include " computations.h" C/C++ distinguishes declaration and definition. Declaration: Tell the compiler what names are available. Definition: Define where the name is stored. 15 16 int main () { 17 std :: cout << "adding via function : 5+11= " << add_values (5,11) << std :: endl ; 18 return 0; 19 } 1 /** code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basic_usage/second_example.cpp 2 * Here comes some documentation : 3 * Adding two integers and returns the result. 4 */ 5 int add_values ( int a, int b); code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basic_usage/computations.h 1 # include " computations.h" 2 3 int add_values ( int a, int b) { 4 return a+b; 5 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basic_usage/computations.cpp Working with C and C++, June 30, 2014 15 Working with C and C++, June 30, 2014 16

Compilation of Two Files Naming Conventions for Files Variant 1: compile & link simultaneously 1 g++ -O3 -g second_example. cpp computations. cpp -o second_v1 Variant 2: Step 1: compile Step 2: link passing the object files to the linker, or passing the library files (a,so) due to the -l argument with -L giving the compiler the library search path. 1 g++ -O3 -g -c second_example. cpp computations. cpp 2 g++ -O3 -g second_example.o computations.o -lm -o second_v2 type C C ++ implementation.c.cpp.cxx.c.cc header.h.h.hpp.hxx Working with C and C++, June 30, 2014 17 Working with C and C++, June 30, 2014 18 Header Files - Best Practices A good header file (almost) never contains definitions. A good header file has lots of comments (on what a function or object does, not on how) since: other editors of files see it frequently, automatic code documentation tools may/will use it. Each header file is typically accompanied by one implementation file. Frequently, header files contain include guards: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c+ +/GRS_2014/src/basic_usage/include_guards.h Working with C and C++, June 30, 2014 19 1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Functions en detail Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Backup Working with C and C++, June 30, 2014 20 2 C ++ as an increment of C Properties of C ++ C 99 C++ 98 C <99 <99 C++ Historically: C ++ designed as an increment of C Design/development influenced by other programming languages C ++ contains considerable amount of constructs that are new/redundant compared to C (casts, new vs. malloc,... ) Working with C and C++, June 30, 2014 21 Working with C and C++, June 30, 2014 22 1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Functions en detail Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Backup Working with C and C++, June 30, 2014 23 3 Basics of C Working with C and C++, June 30, 2014

Syntax vs. Semantics 3.1 Built-in Data Types Syntax = rules for the constructing of sentences in the languages The syntax is (more or less) prescribed by C. Semantics = meaning of sentences, words, or fragments. The semantics is what you had in mind, i.e. the reader has to reconstruct it from your program. Best practices: Use meaningful names! Add documentation, documentation, and documentation! If code is not documented, it does not exist! int integer value (signed) short int integer (typ. 16 bytes) long int integer (typ. 32 bytes) unsigned int int (purely positive) double floating point number (double prec.) float floating point number (single prec.) char character bool boolean type (only C ++) Working with C and C++, June 30, 2014 25 Working with C and C++, June 30, 2014 26 Built-in Data Types - int Built-in Data Types - double 20 int i; 21 int k; 22 i = 5; 23 k = -1; std :: cout << "i+k=" << i+k << std :: endl ; 25 unsigned int l = 25; 26 std :: cout << "k+l=" << k+l << std :: endl ; Here, some C / C ++ syntax obvious: Declaration/definition of variables Assignment of variable values note: = different to == note: garbage value of variable if no assignment! 30 double a; 31 double b; 32 double c; 33 a = 0.145e -07; 34 b = 23. e09 ; 35 c = a+b; 36 std :: cout << c << std :: endl ; Working with C and C++, June 30, 2014 27 Working with C and C++, June 30, 2014 28 Built-in Data Types - float Built-in Data Types - char 40 float d = 3 e38 ; 41 std :: cout << "d=" << d << std :: endl ; 42 d = 3 e39 ; 43 std :: cout << "d=" << d << std :: endl ; 44 float pi = 3.141592654; 45 std :: cout << "pi=" << pi << std :: endl ; Note: default number of printed digits: 6 (change possible, see streams below) 49 char x=65, y= B ; 50 51 std :: cout << x << " " << y << std :: endl ; 52 std :: cout << x+y << std :: endl ; Attention: string manipulation etc. cumbersome in C special data type std::string in C ++ Working with C and C++, June 30, 2014 29 Working with C and C++, June 30, 2014 30 Built-in Data Types - bool Built-in Data Types & Memory Memory no real boolean data type in C actually, int is (mis-)used different historic workarounds but: boolean data type in C ++ (true or false) int x; char y; float z; 21: y // one byte 22; z // four bytes 23; ; 25; 26; x // two bytes? 27; 28: A variable corresponds to memory location and holds a value. Compiler cares for memory layout. Working with C and C++, June 30, 2014 31 Working with C and C++, June 30, 2014 32

Constants 3.2 Memory Organisation (WIN style) 1 i n t ConstantA = 1; 2 double ConstantB = 0. 4 ; 3 double ConstantC = 23.232323; 4 5 void main ( ) { 6... 7 } Static and global variables (Some) Read-only variables Constants (not user accessible) Code Heap Stack Constants are treated similar to source code, i.e. translated by the compiler into bit sequences. Some very simple constants can be embedded into the micro codes (assembler). At startup, all others are loaded into the memory. Appl 1 Appl 2 Reserved by OS (adrs $0, typically 128 kb) Working with C and C++, June 30, 2014 33 Working with C and C++, June 30, 2014 34 Memory Organisation for Variables 3.3 Type Inference Whole memory per application: split up into segments (or sections). Linker can determine their size. Search for free memory: only done for heap data. Other variables: created (and destroyed) one by one on the stack segment. Exception: Variables not declared within main or any other function, but outside. Those are global/static variables held by a different segment. Each object file holds a specification for the segments (sizes). The linker then merges them into one big memory layout. float int double unsigned int Note: casts from supersets to subsets: eventually compiler warnings! Working with C and C++, June 30, 2014 35 Working with C and C++, June 30, 2014 36 Type Inference - Example 1 Type Inference - Example 2 15 # include <iostream > 16 17 int main () { 18 19 // Example 1 20 unsigned int u = 2; 21 int i = 1; 22 double d; 23 d = (u *10) - 0.32; 25 std :: cout << "d(wu) = " << d << std :: endl ; 26 d = (i *10 + u) - 0.32; 27 std :: cout << "d(wi) = " << d << std :: endl ; 28 u = d * 10; 29 std :: cout << "u = " << u << std :: endl ; 32 int a1 = 3; 33 int b1 = 4; 34 double c1 = a1 + b1; 35 36 std :: cout << "c1 = " << c1 << std :: endl ; 37 c1 = 7.0; 38 std :: cout << "c1 = " << c1 << std :: endl ; 39 40 double a2 = 3.0; 41 int b2 = 4; 42 int c2 = a2 + b2; 43 44 std :: cout << "c2 = " << c2 << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/type_inference.cpp code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/type_inference.cpp Working with C and C++, June 30, 2014 37 Working with C and C++, June 30, 2014 38 Type Inference - Type Conversion Pitfall 3.4 Recap: Scopes, Loops & Branches 47 double d0 = 4 / 3; 48 std :: cout << "d0 = " << d0 << std :: endl ; 49 50 double d1 = 4.0 / 3.0; 51 std :: cout << "d1 = " << d1 << std :: endl ; 52 53 double d2 = 4.0 / 3; 54 std :: cout << "d2 = " << d2 << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/type_inference.cpp The concept of the scope: A variable has to be declared within the same brackets { }. Otherwise, compiler searches within the enclosing brackets (not within the neighbours). The brackets define a scope. The outer brackets define an outer scope. Some compilers allow the programmer to redefine variables within subscopes. This hides variables they are not overwritten. Working with C and C++, June 30, 2014 39 Working with C and C++, June 30, 2014 40

Recap: Loops Recap: The For Loop Loops render the programming style applicative programming. Types of loops: while, do-while, for. : should be known. Syntax: 1 while ( expression ) { 2 / / something i n t e l l i g e n t 3 } 4 5 do { 6 / / something i n t e l l i g e n t 7 } while ( expression ) ; 1 f o r ( i n t a=0; a<20; a++) { 2 / / something i n t e l l i g e n t 3 } for statements: opens a new scope Statement int a: creates a new variable (loop counter) within this scope Statement a<20: termination criterion (evaluated before the upcoming iteration) Statement a++: increment of the loop counter Working with C and C++, June 30, 2014 41 Working with C and C++, June 30, 2014 42 What do These Snippets Do? Recap: Branches 20 for ( int a =0; a <20; a ++) { 21 // something intelligent 22 } 23 for ( int a =0; a <20; a ++) { 25 // something intelligent 26 a *=2; 27 } 28 29 for ( int a =1; a <20; a *=2) { 30 // something intelligent 31 } 32 33 for ( int a =0; a <20; a *=2) { 34 // something intelligent 35 } if-then-else constructs: 20 double a =2.5; 21 double b =3.8; 22 23 double max ; if (a < b) { 25 max = b; 26 } 27 else { 28 max = a; 29 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/branches.cpp comparison operators: <, >, <=, >=, ==,!= logical operators:!, &&, Working with C and C++, June 30, 2014 43 Working with C and C++, June 30, 2014 44 Recap: Branches (2) 3.5 Functions switch statement: 33 char c; 34 std :: cout << "please type a character :" << std :: endl ; 35 std :: cin >> c; 36 37 switch (c) { 38 case a : 39 case A : 40 std :: cout << "you typed A " << std :: endl ; 41 break ; 42 case b : 43 case B : 44 std :: cout << "you typed B " << std :: endl ; 45 break ; 46 default : 47 std :: cerr << "l. 47: unknown character!" << std :: endl ; 48 } Syntax of function definitions: 1 returntype functionname ( paramtype paramname ) { 2 / / do something i n t e l l i g e n t 3 } Functions define a scope due to the brackets { } (basis block). Variables of other scopes are not defined within the function. code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/branches.cpp Attention: do not forget the break statement! Working with C and C++, June 30, 2014 45 Working with C and C++, June 30, 2014 46 17 void nothing (void ); // function prototype 18 void nothing2 (); // function prototype 19 void timesx (int x); // function prototype 20 int area (int, int ); // function prototype 21 int area2 (int a, int b); // function prototype 22 23 void nothing ( void ) { std :: cout << "do nothing :-)" << std :: endl ; 25 } 26 void nothing2 () { 27 std :: cout << "do nothing again " << std :: endl ; 28 } 29 void timesx ( int x) { 30 for ( int i =1; i <=x; i ++) { 31 std :: cout << "*" << std :: endl ; 32 } 33 } 34 int area ( int a, int b) { 35 return a*b; 36 } 37 int area2 ( int a, int b) { 38 return a*b; 39 } Functions - Examples code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/functions.cpp Working with C and C++, June 30, 2014 47 17 double foo ( double a, double h) { 18 if (h ==0) { 19 return 0.0; 20 } 21 if (a ==0) 22 return ; // error 23 // do something complicated with a and h return a /10.0; 25 } 26 27 void foo2 ( double a, double h) { 28 //... 29 return 1; // error 30 } Return Statements code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/functions2.cpp Return statement makes the application leave the current function. accepts one argument: the return value (if it is not a void function). may be everywhere in the function. But: multiple return statements often are considered to be bad style. Working with C and C++, June 30, 2014 48

17 int sign ( int a) { 18 // return sign 19 } 20 21 double change_sign ( double b) { 22 // change sign and return new value 23 } 25 int main () { 26 // do something : compute and change signs 27 sign ( -11) ; 28 change_sign (5.3) ; 29 30 return 0; 31 } What is the main Function? code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/functions3.cpp Any program is a collection of functions. They have to have unique signatures (names, see below). Execution always set to the main function. main function returns 0 if it has been successful (error code). This is a UNIX convention. Working with C and C++, June 30, 2014 49 17 int sign ( int a) { 18 // return sign 19 } 20 21 double change_sign ( double b) { 22 // change sign and return new value 23 } 25 int main () { 26 // do something : compute and change signs 27 sign ( -11) ; 28 change_sign (5.3) ; 29 30 return 0; 31 } Functions Some Best Practices code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/functions3.cpp One purpose, one function: Any function should concentrate solely on one job. One page, one function: With a less, one should be able to see the complete function. A function without documentation does not exist! Wolfgang Eckhardt, Functions Tobias Neckel: Object-oriented should have Programming meaningful C++ names (verbs). Working with C and C++, June 30, 2014 50 3.6 Call-by-value vs. Call-by-Reference Questions to be tackled: What happens with parameters in functions when being called? Can functions modify outside variables? What do you know already? Working with C and C++, June 30, 2014 51 15 # include <iostream > 16 17 void foo ( int x) { 18 // do something with x 19 x = 50; 20 std :: cout << "foo (): x = " << x << std :: endl ; 21 } 22 23 int main () { 25 26 int x = 10; 27 foo (x); 28 std :: cout << "main (): x = " << x << std :: endl ; 29 30 return 0; 31 } Call-by-value code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/call_by_value.cpp Computer encounters function call (foo()) with argument x. It stores away all variables, remembers where it has been called from and creates a copy of a. It resets the program counter. Working with C and C++, June 30, 2014 52 Call-by-value In C/C++, parameters (arguments) are passed call-by-value. Functions work on copies of the original variables. The original variables are saved away on the call stack. As soon as the operation terminates, the old variable values are restored. 15 # include <iostream > 16 17 int multiplybytwo ( int x) { 18 x = x *2; 19 return x; 20 } 21 22 23 int main () { The Return Statement and Call-by-value 25 int x = 10; 26 int b = multiplybytwo (x); 27 std :: cout << "main (): x = " << x << std :: endl ; 28 std :: cout << "main (): b = " << b << std :: endl ; 29 30 x = multiplybytwo (x); 31 std :: cout << "main (): x = " << x << std :: endl ; 32 33 return 0; 34 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/call_by_value_return.cpp The return statement takes the value of the function s copy and writes it to the left-hand side of the function invocation. Working with C and C++, June 30, 2014 53 Working with C and C++, June 30, 2014 54 const Modifier 3.7 Signature of a Function We can mark any argument to be a const argument, i.e. the function is not allowed to modify it. 1 void foo ( const i n t a ) { 2... 3 } const allows compiler to optimise code aggressively. const allows you to write bug-safe code (user cannot modify a variable by accident). const closes (some of) the performance gap between C / C ++ and FORTRAN. 1 i n t foo ( ) 2 i n t bar ( ) 3 i n t foo ( i n t a ) 4 i n t foo ( double x ) 5 i n t foo ( i n t a, const double b, double x ) A function is unique due to its name, and due to the number of arguments, and due to the type of the arguments, and due to the const modifiers of its arguments Everything besides the name: signature. name + signature function unique. Attention: return value does not come into play! Working with C and C++, June 30, 2014 55 Working with C and C++, June 30, 2014 56

1 i n t foo ( ) 2 i n t foo ( i n t a ) {} 3 i n t foo ( double a ) {} 4 5... 6 7 foo ( ) ; 8 foo ( 3. 4 ) ; 9 foo ( 4 ) ; overload a function = offer it with different signatures. C / C ++ then automatically tries to find the right signature. Be aware of automatic type conversions! Overloading Memory 21: 22; 20 // int a 23; ; 25; 26; 27; 28: The memory is enumerated using an integer. 3.8 Pointers Pointers are variables that hold the memory number (address) instead of a value. 1 / / holds an i n t ; 2 i n t a ; 3 / / holds address of an i n t 4 i n t * p ; Working with C and C++, June 30, 2014 57 Working with C and C++, June 30, 2014 58 Pointers and Addresses Pointers and the Memory The * operator declares a pointer. 19 int a = 20; 20 int *p; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/pointer.cpp The & operator returns the address of a variable (address operator or reference operator). 22 p = &a; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/pointer.cpp The * operator makes an operation act on the location a pointer points to instead of the pointer itself (dereferencing operator). 26 a += 10; 27 std :: cout << "a = " << a << std :: endl ; 28 (*p) += 10; Memory 21: 22; 20 // int a 23; ; 22 // pointer p 25; 26; 27; 28: int a; a = 20; int *p; p = &a; a++; p++; (*p)++; *p++; // try this at home code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/pointer.cpp Working with C and C++, June 30, 2014 59 Working with C and C++, June 30, 2014 60 1 void foo ( i n t * a ) { 2 ( * a ) ++; 3... When to Use Pointers 4 a++; / / That could not have happened with references 5 } Pointers are difficult to handle (lots of syntactic overhead). We know how to do it, but do collaborators know? Avoid it whenever possible. Use C++ references instead. Application example: We write a fancy compute game for a 2D shooter, i.e. a code working on R 2. 17 double x; 18 double y; 19 20 //... 21 22 /** 23 * Compute scalar product. */ 25 double dotproduct ( 26 const double & x1, 27 const double & x2, 28 const double & y1, 29 const double & y2 30 ) { 31 return x1*y1 + x2*y2; 32 } 3.9 Arrays code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/array.cpp The extension to R 3 induces additional source code. And what if a mathematician wants to handle R n with arbitrary n? Working with C and C++, June 30, 2014 61 Working with C and C++, June 30, 2014 62 Array Declaration Array Access 1 double grade [ 4 ] ; Memory Memory 2 3... 21: 22; // grade[0] 23; // grade[1] ; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 1 double grade [ 4 ] ; 2 3... 21: 22; // grade[0] 23; // grade[1] ; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 4 5 grade [ 0 ] = 1. 3 ; 6 grade [ 2 ] = 3. 3 ; 7 grade [ 3 ] = 1. 0 ; 8 grade [ 1 ] = 4. 0 ; Depending on the context: [] defines the size of an array (definition) [] gives access to individual entries of an array (access). Working with C and C++, June 30, 2014 63 Working with C and C++, June 30, 2014 64

Arrays & Pointers Dot Product Revisited We need a range variable 1 double grade [ 4 ] ; 2 grade [ 0 ] = 1. 3 ; 3 grade [ 2 ] = 3. 3 ; 4 grade [ 3 ] = 1. 0 ; 5 grade [ 1 ] = 4. 0 ; 6 7 double * p = grade ; 8 i f ( grade [ 0 ] = = * p )... / / always t r u e 9 i f ( grade [ 1 ] = = * ( p+1) )... / / always t r u e Name of array == pointer to the first element of array Array element access: internally implies pointer arithmetics and dereferencing Attention pointers: range checks (size of array) not automatically! 1 double dotproduct ( 2 double * x, 3 double * y, 4 i n t n 5 ) { 6 double r e s u l t = 0. 0 ; 7 f o r ( i n t i =0; i <n ; i ++) { 8 r e s u l t += * ( x+ i ) + * ( y+ i ) ; 9 } 10 r e t u r n r e s u l t ; 11 } Working with C and C++, June 30, 2014 65 Working with C and C++, June 30, 2014 66 1 double * grades = new double [ 4 5 ] ; 2 3 delete [ ] grades ; We can create arrays on the heap. Size might be a variable, too. Dynamic Arrays ( C ++ Style) Corresponding delete has to be a delete[]. delete without brackets just deletes the first value. There is a performance reason for two different delete operators. If we omit delete, we will get a memory leak. If we use the array after delete or before new, it points to garbage (remember: grades is only a pointer). Working with C and C++, June 30, 2014 67 19 double matrix [4][4]; 20 Multidimensional Arrays 21 for ( int i =0; i <4; i ++) { 22 for ( int j =0; j <4; j ++) { 23 // conditional assignment matrix [i][j] = i==j? 1.0 : 0.0; 25 std :: cout << "m["<<i<<"]["<<j<<"]=" << matrix [i][j] << std :: endl ; 26 } 27 } 28 matrix [2][1] = 5.0; 29 // matrix [12] = 12.0; // does not compile! 30 * matrix [1] = 12.0; 31 * matrix [17] = 12.0; // compiles, but...!? try compile with -O0 code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/array_multidim.cpp What is the semantics of the for loop? Multidimensional arrays basically are flat arrays. C/C++ uses row-major format (different to FORTRAN), i.e. if you pass arrays to FORTRAN code you might have to transpose the array first. Working with C and C++, June 30, 2014 68 Outlook C/C++ Arrays vs. FORTRAN FORTRAN is claimed to be the language for linear algebra as it is faster. FORTRAN does not provide pointers and dynamic data structures. Consequently, compiler can keep track of who has access where. Consequently, compiler can optimise aggressively (it tries to keep book of all possible values an array could have side-effect!). So, it is all a matter of exclusivity and the const operator. Working with C and C++, June 30, 2014 69 1 Basic Usage From Text Files to Binary Code Header Files 2 C ++ as an increment of C 3 Basics of C Built-in Data Types Memory Organisation Type Inference Recap: Scopes, Loops & Branches Functions Call-by-value vs. Call-by-reference Functions en detail Pointers Arrays 4 From C to C ++ (Extensions) Namespaces References Using C Libraries in C ++ Backup Working with C and C++, June 30, 2014 70 4 From C to C ++ (Extensions) 4.1 Namespaces: Multiple Declarations with Different Context 14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 /** 18 * Calculates force between two particles ( Lennard - Jones ) 19 */ 20 double getforce ( const double & distance ); 21 #endif // _IDENTIFIER_FOR_HEADER_A_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_a_no.h 14 // This is header B 15 # ifndef _IDENTIFIER_FOR_HEADER_B_H_ 16 # define _IDENTIFIER_FOR_HEADER_B_H_ 17 /** 18 * Calculates force between two particles ( WCA model ) 19 */ 20 double getforce ( const double & distance ); 21 #endif // _IDENTIFIER_FOR_HEADER_B_H_ Working with C and C++, June 30, 2014 71 code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_b_no.h Sometimes, functions and variables have the same name as they were developed by different authors and written into different Wolfgang Eckhardt, files. Tobias Neckel: Object-oriented Programming in C++ Working with C and C++, June 30, 2014 72

14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 namespace lennardjones { 18 /** 19 * Calculates force between two particles ( Lennard - Jones ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 #endif // _IDENTIFIER_FOR_HEADER_A_H_ Namespaces (2) code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_a.h 14 // This is header B 15 # ifndef _IDENTIFIER_FOR_HEADER_B_H_ 16 # define _IDENTIFIER_FOR_HEADER_B_H_ 17 namespace wca { 18 /** 19 * Calculates force between two particles ( WCA model ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 #endif // _IDENTIFIER_FOR_HEADER_B_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_b.h Namespaces: group variables, constants, and functions into logic Wolfgangsubsets. Eckhardt, Tobias Neckel: Object-oriented Programming in C++ Working with C and C++, June 30, 2014 73 Using Namespaces 14 // This is header A 15 # ifndef _IDENTIFIER_FOR_HEADER_A_H_ 16 # define _IDENTIFIER_FOR_HEADER_A_H_ 17 namespace lennardjones { 18 /** 19 * Calculates force between two particles ( Lennard - Jones ) 20 */ 21 double getforce ( const double & distance ); 22 } 23 #endif // _IDENTIFIER_FOR_HEADER_A_H_ code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_a.h 14 // This is the implementation 15 # include " lennardjones.h" 16 17 double lennardjones :: getforce ( const double & distance ) { 18 \ ldots 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/c_to_c++/namespaces_a.cpp Namespaces are predecessors of the identifier. Namespaces can be embedded into each other. Working with C and C++, June 30, 2014 74 17 int multiplybytwo ( int & x) { 18 x = x *2; 19 return x; 20 } 21 22 int main () { 23 int x = 10; 25 int b = multiplybytwo (x); 26 std :: cout << "main (): x = " << x << std :: endl ; 27 std :: cout << "main (): b = " << b << std :: endl ; 28 29 x = multiplybytwo (x); 30 std :: cout << "main (): x = " << x << std :: endl ; 31 32 return 0; 33 } 4.2 Call-by-reference code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/call_by_value_reference.cpp The & operator is the reference operator. It tells C/C++ to pass the argument with call-by-reference semantics. Then, C/C++ does not create a copy, but the operation works on Wolfgang Eckhardt, the Tobias original Neckel: Object-oriented variable. Programming in C++ Working with C and C++, June 30, 2014 75 Exercise: Swap Two Variables 1 void main ( ) { 2 i n t a = 3; 3 i n t b = 4; 4 / / interchange a and b 5 a = b ; 6 b = a ; 7 std : : cout << a << std : : endl ; 8 std : : cout << b << std : : endl ; 9 } Fix the code above. Extract the swap functionality in a function of its own. Working with C and C++, June 30, 2014 76 const References 4.3 Using C Libraries in C ++ 1 void foo ( i n t a, i n t b ) { 2... 3 } 4 5 void bar ( i n t & a, i n t & b ) { 6... 7 } 8 9 void e f f i c i e n t F o o ( const i n t & a, const i n t & b ) { 10... 11 } const references avoid side effects! (const) references belong to the signature overloading! Working with C and C++, June 30, 2014 77 C 99 C++ 98 C ++: Large standard library in comparison to C In principle, all C headers in C ++ usable Naming conventions of headers: 1 # include <math. h> => # include <cmath> 2 # i n c l u d e <s t d l i b. h> => # i n c l u d e <c s t d l i b > Much more in the upcoming days. Working with C and C++, June 30, 2014 78 some stuff that may be interesting but is not covered in the lecture 4.4Backup 1 void foo ( i n t a=3) ; 2 void bar ( ) ; Default Arguments of Functions 3 void bar ( i n t b=3) ; / / not allowed 4 void tee1 ( i n t c, double d =2.0) ; 5 void tee2 ( i n t c =2, double d ) ; / / not allowed 6 void tee3 ( i n t c =2, double d =4.0) ; 7 8... 9 foo ( ) ; 10 foo ( 7 ) ; 11 tee3 ( ) ; 12 tee1 ( 1 ) ; 13 tee1 ( 1, 4. 0 ) ; C ++ supports default arguments. Overloaded functions may not work! All default arguments have to be at the end of the argument list. Working with C and C++, June 30, 2014 79 Working with C and C++, June 30, 2014 80

The pointer operator binds to the right neighbour. Pointer Syntax Pointers and Scopes 1 i n t a ; 2 i n t * b1 ; 3 i n t * b2 ; 4 i n t * b3 ; 5 i n t * c1, c2 ; 6 i n t * c3, * c4 ; 7 i n t * c5, c6 ; 8 i n t * c7, * c8 ; 9 i n t * * c9 ; 10 11 c7 = c8 ; 12 c7 = * c8 ; / / does not work with a l l compilers 13 * c7 = c8 ; / / does not work with a l l compilers 14 * c7 = * c8 ; By the way, often people write int* p=0; to make the pointer point to nothing. However, also int* p = 20; would be fine (and for almost 100 percent is a bug). Working with C and C++, June 30, 2014 81 1 i n t * p ; 2 f o r ( i n t i =0; i <2; i ++) { 3 i n t a = 2 * i ; 4 p = &a ; 5 6 std : : cout << a << std : : endl ; 7 std : : cout << * p << std : : endl 8 } 9 std : : cout << a << std : : endl ; / / does t h i s work? 10 std : : cout << * p << std : : endl ; / / does t h i s work? With pointers, we can violate the end-of-scope rules, i.e. we can access variables that do not exist anymore. This is the principle of all these buffer overrun malware codes. Working with C and C++, June 30, 2014 82 Array Arguments 19 double computeaverage ( double grade [], int numberofgrades ) { 20 //... 21 } 22 23 double computeaverage ( const double grade [], int numberofgrades ) { //... 25 } 26 27 double computeaverage ( const double * grade, int numberofgrades ) { 28 //... 29 } 30 31 double computeaverage ( const double * const grade, int numberofgrades ) { 32 //... 33 } 34 35 double computeaverage ( double const * const grade, int numberofgrades ) { 36 //... 37 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/array_arguments.cpp This time, the user is not allowed to modify any entry of grade. Working with C and C++, June 30, 2014 83 19 int gradesbsc, gradesmsc [5]; 20 21 gradesmsc [5] = 2.3; 22 gradesmsc [3]++; 23 int * p0 = gradesmsc ; int * p1 = & gradesmsc [0]; 25 int * p2 = & gradesmsc [1]; 26 gradesmsc ++; // does not work 27 p2 ++; // arrrgh 28 29 return 0; Pitfalls code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basics_c/array_pitfalls.cpp Working with C and C++, June 30, 2014 84

1 The of Object Orientation Object-oriented Programming in C++ Object Orientation in C++ Wolfgang Eckhardt, Tobias Neckel July 1, 2014 Object Orientation in C++, July 1, 2014 1 Object Orientation in C++, July 1, 2014 3 What Is an Object? a car a cat a chair... a molecule a star a galaxy... 1.1 Definition of Objects How to Program Object-orientedly Change your way of thinking Change your point of view It is not just a technical question! Good designs requires considerable experience! anything that represents a real thing anything that represents an abstract thing anything which has some properties Object Orientation in C++, July 1, 2014 4 Object Orientation in C++, July 1, 2014 5 Classes A class is similiar to the definition of a type Specifies properties of the objects to be created 1.2 Classes vs. Objects Data to be stored once for all objects (class/static variable) Data to be stored in each object (member variables) Operations to be done with objects (member functions/methods) Represents a class of things/objects Instances / Objects An instance/object is a concrete thing of the type of a class A class specifies properties, an object has specific values for the specified properties state of an object For each class, there can be an arbitrary number of objects Each object belongs to exactly one class (exception: polymorphism, day 3) Object Orientation in C++, July 1, 2014 6 Definition Oracle, The Java Tutorials Object: Definition State: the set of values of member variables/fields (built-in datatypes and other objects) at a specific point in time Behaviour: Member functions/methods operate on the internal state of the object, primary mechanism for object-to-object communication Object Orientation in C++, July 1, 2014 7 Oracle, The Java Tutorials Example: Bike State: Speed, Revolutions per Minute, Gear,.. Behaviour: Change gears, change cadence, brake,.. Object: Example Object Orientation in C++, July 1, 2014 8 Pros 1.3 Why Object Orientation? Modularity: Implementation of different objects usually written independently. Information hiding: Internal implementation remains hidden from the outside world (can be changed easily even for heavy used objects) Code reuse: Object (re-)use: you only have to understand the member-functions visible to you (interfaces in software projects and/or libraries) Inheritance (details below) Cons Performance: Wrong usage of OO-language constructs might come with a significant overhead. Code complexity: Be careful: unclever OO design problems in maintenance, extensibility, etc.) Object Orientation in C++, July 1, 2014 9

2 Objects in C ++ 2.1 Overview: Bikes as Objects Bikes as Objects Task: Model a bike in C ++ Goal: Learn the C ++ syntax on the way Design Gear Shift Bike State: current gear, #gears Behaviour: increase gear, decrease gear, get current gear State: current speed, revolutions per minute, gear shift Behaviour: change gear, brake, change cadence Design Gear Shift Overview Bike State: current gear, #gears Behaviour: increase gear, decrease gear, get current gear State: current speed, revolutions per minute, gear shift Behaviour: change gear, brake, change cadence Next Skeleton (header file) of the bike class with member variables, member functions and access control. Object Orientation in C++, July 1, 2014 11 Object Orientation in C++, July 1, 2014 12 Bike.h - The class Keyword Bike.h - State: Member Variables 17 # ifndef BIKE_H_ 18 # define BIKE_H_ 19 20 # include <cmath > 21 # include <iostream > 22 23 # include " GearShift.h" 25 class Bike { 72 }; 73 74 #endif // BIKE_H_ Keyword code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.h class defines a class in C ++ frame for OO concepts (member variables, member functions, inheritance,... ) 25 class Bike { 26 // private : 27 //! current speed 28 float m_speed ; 29 30 //! current rpm 31 float m_revolutions ; 32 33 //! gear shift 34 GearShift m_gearshift ; 72 }; State code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.h Member variables define the state of an object. Member variable can be built-in or custom objects. Object Orientation in C++, July 1, 2014 13 Object Orientation in C++, July 1, 2014 14 Relationships between Objects: Part-Of Object Member Variables model Part-Of Part-Of releationship Object A is with object B in an part-of releationship, if A is part of B (A is one of the parts the machinery of B is assembled of). Example: Object gear shift can be modeled in a part-of relation to the object bike. Object Orientation in C++, July 1, 2014 15 Object Member Variables OO-programming: allows objects to be build of other objects not only built-in data-types allows for a modular implementation and code reuse Object Orientation in C++, July 1, 2014 16 25 class Bike { 36 public : 37 /** 38 * Constructor 39 * Bike.h - Behaviour: Member Functions 40 * @param i_numberofgears # gears 41 **/ 42 Bike ( int i_numberofgears ); 43 44 /** 45 * Destructor 46 **/ 47 ~ Bike (); 48 49 /** 50 * Changes the gear to the closest possible gear. 51 * 52 * @param i_gear gear to change to. 53 **/ 54 void changegear ( int i_gear ); 72 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.h Object Orientation in C++, July 1, 2014 17 25 class Bike { 36 public : Bike.h - Behaviour: Member Functions (2) 56 /** 57 * Brakes the bike. 58 **/ 59 void brake (); 60 61 /** 62 * Accelerates the bike. 63 * 64 * @param i_rpm revolutions per minute. 65 **/ 66 void changecadence ( float i_rpm ); 72 }; Behaviour code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.h Member functions: mutator methods: change internal state of an object (often setxxx()) Object Orientation in C++, July 1, 2014 18

Bike.h - Behaviour: Member Functions (3) Bike.h - Access Control 25 class Bike { 36 public : 67 68 /** 69 * Prints status of our bike. 70 **/ 71 void printinformation () const ; 72 }; Behaviour code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.h Member functions: accessor methods give access (read-only) to the state of an object (often getxxx()) 25 class Bike { 26 // private : 27 //! current speed 28 float m_speed ; 36 public : 37 /** 38 * Constructor 39 * 40 * @param i_numberofgears # gears 41 **/ 42 Bike ( int i_numberofgears ); Accessibility Restrictive access control: helps to write clean code & uses compiler to enforce interfaces. private: Members public: Anyone Object Orientation in C++, July 1, 2014 19 Object Orientation in C++, July 1, 2014 20 Information Hiding 2.2 Overview: Bikes as Objects Users/developers have restricted access to objects/classes avoid side effects! (you don t want a user to change the gravity constant of the earth, etc.) reduce code complexity in usage (you only need to care about what you can see) reduce code complexity in development (accessor methods, e.g.: rename a member variable) Design Gear Shift Overview Bike State: current gear, #gears Behaviour: increase gear, decrease gear, get current gear State: current speed, revolutions per minute, gear shift Behaviour: change gear, brake, change cadence Previous Skeleton (header file) of the Bike class with member variables, member functions and access control. Next Implementation (source file) of the Bike class & runner. Object Orientation in C++, July 1, 2014 21 Object Orientation in C++, July 1, 2014 22 Bike.cpp - Constructor Bike.cpp - Member Initialisation List 17 # include " Bike.h" 18 19 Bike :: Bike ( int i_numberofgears ): 20 m_speed (0), 21 m_revolutions (0), 22 m_gearshift ( i_numberofgears ) { 23 std :: cout << "bike with " << i_numberofgears << " gears constructed " << std :: endl ; 25 }; Properties code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.cpp Called whenever an object is created More than one constructor (with different syntax) possible; no return type If none is specified, the compiler generates one (default constructor) 19 Bike :: Bike ( int i_numberofgears ): 20 m_speed (0), 21 m_revolutions (0), 22 m_gearshift ( i_numberofgears ) { Properties code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.cpp Per default the default constructor is called for all members Some member types have to be initialised in the member initialisation list: references non-static const member class members w\o default constructors base class members (Performance gains possible: construction vs. assignment) Object Orientation in C++, July 1, 2014 23 Object Orientation in C++, July 1, 2014 27 Bike ::~ Bike () { 28 std :: cout << "bike destroyed :(" << std :: endl ; 29 } Properties Bike.cpp - Destructor code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/bike.cpp Called whenever an object is destroyed Clean up of the object (could free dyn. allocated memory, e.g.) No arguments or return type If no destructor is specified, the compiler generates a default one Bike.cpp - Member Functions 31 void Bike :: changegear ( int i_gear ) { 32 if( i_gear < m_gearshift. getcurrentgear () ) { 33 // decrease gears until best possible gear is reached 34 while ( m_gearshift. decreasegear () ) { 35 if( i_gear == m_gearshift. getcurrentgear () ) break ; 36 } 37 } 38 else if( i_gear > m_gearshift. getcurrentgear () ) { 39 // increase gearse until best possible gear is reached 40 while ( m_gearshift. increasegear () ) { 41 if( i_gear == m_gearshift. getcurrentgear () ) break ; 42 } 43 } 44 } 45 46 void Bike :: brake () { 47 m_speed = std :: max ( 0.f, m_speed - 5.f ); 48 m_revolutions = m_speed * 25. f; 49 } 50 51 void Bike :: changecadence ( float i_rpm ) { 52 m_revolutions = std :: max ( 0.f, i_rpm ); 53 m_speed = m_revolutions * m_gearshift. getcurrentgear () / 25. f; 54 } Object Orientation in C++, July 1, 2014 25 Object Orientation in C++, July 1, 2014 26

Bike.cpp - Member Functions (2) 2.3 Runner: Instantiating Objects 56 void Bike :: printinformation () const { 57 std :: cout << "speed : " << m_speed << std :: endl 58 << "rpms : " << m_revolutions << std :: endl 59 << " gear : " << m_gearshift. getcurrentgear () 60 << std :: endl ; 61 } Properties accessor member functions: const forbids modification of member variables (details later and in the tutorials) 17 # include " Bike.h" 18 19 int main () { 20 // construct two bikes 21 Bike l_mybike ( 20 ); 22 Bike * l_myfriendsbike = new Bike ( 15 ); 39 delete l_myfriendsbike ; 40 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/bike/runner.cpp 2 Variants: Direct instantiation via constructor call Dynamic memory allocation in C ++: via new-keyword (more typesafe and calls constructors) Hint: Always delete what you new, and free what you malloc. Don t mix new with free or malloc with delete! Object Orientation in C++, July 1, 2014 27 Object Orientation in C++, July 1, 2014 28 17 # include " Bike.h" 18 19 int main () { 20 // construct two bikes 21 Bike l_mybike ( 20 ); 22 Bike * l_myfriendsbike = new Bike ( 15 ); 23 // print their initial status 25 l_mybike. printinformation (); 26 l_myfriendsbike -> printinformation (); 27 28 // go on a bike tour with a friend 29 l_mybike. changegear ( 16 ); 30 l_mybike. changecadence ( 16.5 ); 31 l_myfriendsbike -> changegear ( 9 ); 32 l_myfriendsbike -> changecadence ( 29.8 ); 33 34 // print information 35 l_mybike. printinformation (); 36 l_myfriendsbike -> printinformation (); 37 38 // free dynamic memory 39 delete l_myfriendsbike ; 40 } Runner: Using bikes up to now: member variables member functions 2.4 Special Members How about variables that exist only once per class (not per object)? How about functions that do not modify objects? Object Orientation in C++, July 1, 2014 29 Object Orientation in C++, July 1, 2014 30 19 class SimpleClass { 20 // private : 21 static int s_simplecounter ; 22 23 public : SimpleClass () { 25 s_simplecounter ++; Static Members 26 std :: cout << "ctr in constr =" << s_simplecounter << std :: endl ; 27 }; 28 29 ~ SimpleClass () { 30 s_simplecounter - -; 31 std :: cout << "ctr in destr =" << s_simplecounter << std :: endl ; 32 }; 33 }; 34 35 int SimpleClass :: s_simplecounter = 0; 36 37 int main () { 38 SimpleClass l_simple1 ; 39 { 40 SimpleClass l_simple2 ; 41 } 42 SimpleClass l_simple3 ; 43 } Object Orientation in C++, July 1, 2014 31 19 class SimpleClass { 20 // private : 21 static int s_simplecounter ; 22 23 public : SimpleClass () { 25 s_simplecounter ++; Static Members (2) 26 std :: cout << "ctr in constr =" << s_simplecounter << std :: endl ; 27 }; 28 29 ~ SimpleClass () { 30 s_simplecounter - -; 31 std :: cout << "ctr in destr =" << s_simplecounter << std :: endl ; 32 }; 33 }; 34 35 int SimpleClass :: s_simplecounter = 0; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/static_member_variable.cpp A class can have static member variables, which are single locations in memory shared by all instances of the class. Object Orientation in C++, July 1, 2014 32 19 class SimpleClass { 20 // private : 21 static int s_simplecounter ; 22 Static Member Functions 23 public : static void increasecounter (){ s_simplecounter ++; }; 25 static void printcounter (){ std :: cout << s_simplecounter << std :: endl ; }; 26 }; 27 28 int SimpleClass :: s_simplecounter = 1; 29 30 int main () { 31 SimpleClass :: printcounter (); 32 SimpleClass :: increasecounter (); 33 SimpleClass :: printcounter (); 34 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/static_member_function.cpp Static member functions: accessible independently of a single instance of a class non-static members or this-pointer can t be accessed Object Orientation in C++, July 1, 2014 33 17 class SimpleClass { 18 // private : 19 const int m_a ; 20 21 public : 22 SimpleClass ( int i_a ): m_a ( i_a ) { 23 // forbidden assignment // m_a = 10; 25 }; 26 }; 27 28 int main () { 29 SimpleClass l_simple ( 15 ); 30 } Const Members code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/const_member_variable.cpp A class can have const member variables: can t be changed after initialization have to be set in the member initialisation list. Object Orientation in C++, July 1, 2014 34

Const Member Functions 3 Inheritance 17 class SimpleClass { 18 // private : 19 int m_a ; 20 21 public : 22 void simplefunctions () const { 23 // forbidden assignment // m_a = 5; 25 } 26 }; 27 28 int main () { 29 SimpleClass l_simple ; 30 l_simple. simplefunctions (); 31 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/const_member_function.cpp A class can have const member functions, which are not allowed to change the member variables/state of an object. Hint: The position of the const qualifier is crucial ( tutorials). Object Orientation in C++, July 1, 2014 35 Object Orientation in C++, July 1, 2014 37 Inheritance in Real Life object Object Orientation in C++, July 1, 2014 38 Inheritance in Real Life sunbed Audi Golf car VW Polo c table chair table chair BMW Phaeton furniture machine furniture machine furniture mac laptop object comp. object comp. desktop oak obj vectorc. cypress plant animal plant animal plant cluster beech tree mammal reptile tree mam croc. daisy flower horse snake flower tulip donkey mule rose cat Object Orientation in C++, July 1, 2014 39 Relationships between Objects: Is-A Is-A models Inheritance Oracle, The Java Tutorials Is-A releationship Object A is with object B in an is-a releationship, if A behaves like B, but adds additional features (B is a blueprint for A); Example: Objects mountain bike and road bike are modeled to be in a is-a relation to the object bicycle Object Orientation in C++, July 1, 2014 40 Inheritance Oracle, The Java Tutorials OO-programming allows to inherit states and behaviour from other objects; allows for abstraction/specialization in the implementation Object Orientation in C++, July 1, 2014 41 Sketch Understanding Is-A : Rectangles Inheritance in OO Code Rectangles Rectangle: increasesize() Square is-a Rectangle Rectangle.increaseSize(), Square.increaseSize()? Classes can inherit from a base class they are derived classes / subclasses of the base clase All classes can be specialised All classes together form a taxonomy/hierarchy of classes Methodes of the base class can be kept and used, or can be defined newly (overwriting, details see day 3) Object Orientation in C++, July 1, 2014 42 Object Orientation in C++, July 1, 2014 43

Star(..); virtual ~Star(); virtual double getsurfacearea() const; Shape( int i_color = 0 ); virtual ~Shape(); int getcolor() const; virtual double getsurfacearea() const; Circle( double i_radius ); virtual ~Circle(); virtual double getsurfacearea() const; Rectangle( double i_width, double i_height, int i_color = 0 ); virtual ~Rectangle(); virtual double getsurfacearea() const; 3.2 Inheritance: Interface and Implementation Sketch Shape Sketch Inheritance: Interface and Implementation (2) Shape Shape( int i_color = 0 ); virtual ~Shape(); int getcolor() const; Star Rectangle virtual double getsurfacearea() const; Star Rectangle Star(..); Rectangle( double i_width, virtual ~Star(); double i_height, virtual double Circle int i_color = 0 ); getsurfacearea() const; virtual ~Rectangle(); virtual double getsurfacearea() const; Circle( double i_radius ); virtual ~Circle(); virtual double getsurfacearea() const; Object Orientation in C++, July 1, 2014 44 Circle Inheritance splits into: Function interfaces and function implementations Allows for three different type implementations: Implementation provided by base class Default-implementation provided base class (can be overwritten) Interface provided by base class (needs to be implemented) Object Orientation in C++, July 1, 2014 45 3.3 Inheritance in C ++: Basic Syntax Shape.cpp - A Bit More Complex 19 class Shape { 20 // private : 21 public : 22 Shape () { 23 std :: cout << "constructed a new shape " << std :: endl ; } 25 26 virtual ~ Shape () {}; 27 }; 28 29 class Star : public Shape {}; 30 class Circle : public Shape {}; 31 class Rectangle : public Shape {}; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/basics.cpp Shape is the base class for the derived classes Star, Circle and Rectangle 23 class Shape { // private : 25 int m_color ; 26 27 public : 28 Shape ( int i_color =0 ): 29 m_color ( i_color ) {}; 30 virtual ~ Shape () {}; 31 32 int getcolor () const { return m_color ; }; 39 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp Object Orientation in C++, July 1, 2014 46 Object Orientation in C++, July 1, 2014 47 Inheritance - Implementing a Child Class 41 class Circle : public Shape { 42 // private : 43 double m_radius ; 44 45 public : 46 Circle ( double i_radius ): 47 Shape (), m_radius ( i_radius ) { 48 std :: cout << "constructed a circle, radius : " 49 << m_radius << std :: endl ; 50 }; 51 virtual ~ Circle () {}; 57 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp Accessibility Circle inherits from Shape note class definition Note: call of base class constructor in initialisation list Object Orientation in C++, July 1, 2014 48 41 class Circle : public Shape { 42 // private : 43 double m_radius ; 44 45 public : 46 Circle ( double i_radius ): 47 Shape (), m_radius ( i_radius ) { 48 std :: cout << "constructed a circle, radius : " 49 << m_radius << std :: endl ; 50 }; 51 virtual ~ Circle () {}; 57 }; Inheritance - Access Control code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual.cpp Accessibility Restrictive access control helps to write clean code and uses the compiler to enforce your interfaces. private: Members protected: Members of the class & of derived classes public: Anyone Object Orientation in C++, July 1, 2014 49 4 Backup 4.1 Switching Off the Lifecycle Management 1 double * p ; some stuff that may be interesting but is not covered in the lecture 2 3 p = new double ; / / now, p p o i n t s to an e x i s t i n g new v a r i a b l e 4 5 * p = 20; 6 7 delete p ; / / now var iab le i s freed, but p s t i l l p o i n t s 8 / / to t h i s v a r i a b l e. 9 10 * p = 30; The value 20 in the memory is an anonymous variable as it doesn t have a name we can reach it only through a pointer. Object Orientation in C++, July 1, 2014 51 Object Orientation in C++, July 1, 2014 52

1 double * p ; 2 3 f o r ( i n t i =0; i <20; i ++) { 4 p = new double ; 5 } 6 7 delete p ; 1 f o r ( i n t i =0; i <20; i ++) { 2 double * p = new double ; 3 } Two Memory Leaks The upper operation creates 20 doubles on the heap, but it destroys only one double in the end. Consequently, the remaining 19 doubles are lost for the future program execution. Let s sketch the memory layout! The second one destroys the pointer but not the space where the pointer is pointing to. This is why many applications crash after Wolfgangseveral Eckhardt, Tobias hours Neckel: of Object-oriented execution. Programming in C++ Object Orientation in C++, July 1, 2014 53 Birds Understanding is-a : Birds Bird: fly() Penguin is-a bird Bird.fly(), Penguin.fly()? What happenend? Problem of our intuotion/language, birds fly means in general birds have the ability to fly Correct model, if our project contains no non-flying bird and will not contain non-flying birds in future Birds (2) Bird FlyingBird is-a Bird: fly() NonFlyingBird is-a Bird Penguin is-as a NonFlyingBird FlyingBird.fly() NonFlyingBird.fly(), Peguin.fly() Object Orientation in C++, July 1, 2014 54 4.2 Modellierung mit UML Flussdiagramme Nur geeignet für kleine Algorithmen Keine Darstellung von Klassenhierarchien Keine Darstellung von Datenabhängigkeiten... UML: Unified Modeling Language visuelle Modellierungssprache Sprache unterstützt unterschiedliche Diagrammtypen Software wird über diese Diagramme/Modelle spezifiziert Kann als Basis für die Dokumentation dienen Automatische Code-Generierung möglich Auch für sonstige betriebliche Abläufe geeignet Object Orientation in C++, July 1, 2014 55 Strukturdiagramme Klassendiagramm Objektdiagramm Kompositionsstrukturdiagramm Komponentendiagramm Verteilungsdiagramm Paketdiagramm Profildiagramm Verhaltensdiagramme Aktivitätsdiagramm Anwendungsfalldiagramm (Use-Cases) Interaktionsübersichtsdiagramm Kommunikationsdiagramm Sequenzdiagramm Zeitverlaufsdiagramm Zustandsdiagramm Object Orientation in C++, July 1, 2014 56 Klassendiagramm Einzelne Klasse Klasse dargestellt durch Rechteck Horizontale Unterteilung in drei Bereiche Oberster Bereich: Klassenname Mittlerer Bereich: Attribute/Variablen Unterer Bereich: Methoden Klassenname + public_vars private_vars + public_methods private_methods Syntax der Klassenbeschreibung Name von Klasse/Variablen/Methoden frei wählbar +: public Variable/Methode (optional) -: private Variable/Methode (optional) Für Variablen kann der Typ angegeben werden (nach :) Für Methoden kann der Rückgabewert angegeben werden (nach :) Object Orientation in C++, July 1, 2014 57 Object Orientation in C++, July 1, 2014 58 Vererbung Darstellung durch Pfeil mit geschlossener Spitze ist ein - Beziehung Pfeil von spezialisierter Klasse zur Vaterklasse Fahrzeug Assoziation Semantischer Zusammenhang zwischen Klassen Beschreibung der Assoziation neben dem Pfeil Vorlesung liest hört Auto Motorrad Dozent Student Object Orientation in C++, July 1, 2014 59 Object Orientation in C++, July 1, 2014 60

Aggregation und Komposition Aggregation (leere Raute): hat ein Komposition (volle Raute): enthält ein Angabe der Anzahl möglich Fahrzeug 1 5 Besitzer Türen Object Orientation in C++, July 1, 2014 61

Star(..); virtual ~Star(); virtual double getsurfacearea() const; Shape( int i_color = 0 ); virtual ~Shape(); int getcolor() const; virtual double getsurfacearea() const; Circle( double i_radius ); virtual ~Circle(); virtual double getsurfacearea() const; Rectangle( double i_width, double i_height, int i_color = 0 ); virtual ~Rectangle(); virtual double getsurfacearea() const; 1 Inheritance and Polymorphism Sketch Object-oriented Programming in C++ Shape Details of Object Orientation in C++ Shape( int i_color = 0 ); virtual ~Shape(); int getcolor() const; Wolfgang Eckhardt, Tobias Neckel July 2, 2014 Star virtual double getsurfacearea() const; Rectangle Star(..); virtual ~Star(); virtual double getsurfacearea() const; Circle Rectangle( double i_width, double i_height, int i_color = 0 ); virtual ~Rectangle(); virtual double getsurfacearea() const; Circle( double i_radius ); virtual ~Circle(); virtual double getsurfacearea() const; Details of Object Orientation in C++, July 2, 2014 1 Details of Object Orientation in C++, July 2, 2014 3 Sketch 1.1 Implementations and Interfaces Star Shape Circle Rectangle Inheritance splits into: Function interfaces and function implementations Allows for three different type implementations: Implementation provided by base class Default-implementation provided base class (can be overwritten) Interface provided by base class (needs to be implemented) Details of Object Orientation in C++, July 2, 2014 4 Implementations and Interfaces (2) - Shape.h 17 class Shape { 18 // private : 19 int m_color ; 20 21 public : 22 Shape ( int i_color =0 ); 23 virtual ~ Shape (); 25 int getcolor () const ; 26 27 // purely virtual function 28 virtual double getsurfacearea () const = 0; 29 30 // virtual function with default implementation 31 // virtual double getsurfacearea () const ; 32 }; Keyword code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/shape.h virtual allows for interfaces and default implementations Non-virtual functions are resolved statically at compile time, virtual functions dynamically at run time Details of Object Orientation in C++, July 2, 2014 5 Implementations and Interfaces (3) - Circle.h Implementations and Interfaces (4) - Rectangle.h 18 class Circle : public Shape { 19 // private : 20 double m_radius ; 21 22 public : 23 Circle ( double i_radius ); virtual ~ Circle (); 25 26 virtual double getsurfacearea () const ; 27 28 // allowed, but usually bad practice.. 29 // int getcolor () const ; 30 }; Interfaces/pure virtual functions have to be implemented in derived classes; virtual interfaces can be overwritten; non-virtual usually shouldn t 17 class Rectangle : public Shape { 18 // private : 19 double m_width, m_height ; 20 public : 21 Rectangle ( double i_width, double i_height, int i_color = 0 ); 22 virtual ~ Rectangle (); 23 virtual double getsurfacearea () const ; 25 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/rectangle.h Interfaces/pure virtual functions have to be implemented in derived classes; virtual interfaces can be overwritten; non-virtual usually shouldn t Details of Object Orientation in C++, July 2, 2014 6 Details of Object Orientation in C++, July 2, 2014 7 Implementations and Interfaces (5) - *.cpp 15 Shape :: Shape ( int i_color ): 16 m_color ( i_color ) { 17 } 18 19 Shape ::~ Shape (){ 20 } 21 22 int Shape :: getcolor () const { 23 return m_color ; } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/shape.cpp 17 Circle :: Circle ( double i_radius ): 18 Shape (), m_radius ( i_radius ) { 19 std :: cout << "constructed a circle, radius : " << m_radius << std :: endl ; 20 } 21 22 Circle ::~ Circle (){ 23 } 25 double Circle :: getsurfacearea () const { 26 return M_PI * m_radius * m_radius ; 27 } Implementations and Interfaces (6) - *.cpp 16 Rectangle :: Rectangle ( double i_width, double i_height, int i_color ): 17 Shape ( i_color ), m_width ( i_width ), m_height ( i_height ) { 18 std :: cout << "constructed rectangle, width /height : " 19 << m_width << "/" << m_height << std :: endl ; 20 } 21 22 Rectangle ::~ Rectangle () { 23 } 25 double Rectangle :: getsurfacearea () const { 26 return m_width * m_height ; 27 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/rectangle.cpp code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/circle.cpp Details of Object Orientation in C++, July 2, 2014 8 Details of Object Orientation in C++, July 2, 2014 9

18 int main () { 19 Circle l_circle ( 2.3 ); 20 Rectangle l_rectangle ( 4.2, 1.8, 3 ); 21 22 Shape * l_shapes [2]; 23 l_shapes [0] = & l_circle ; l_shapes [1] = & l_rectangle ; 25 Implementations and Interfaces (7) 26 for ( int l_shapeid = 0; l_shapeid < 2; l_shapeid ++ ) { 27 std :: cout << l_shapes [l_shapeid ]-> getcolor () << ", " 28 << l_shapes [l_shapeid ]-> getsurfacearea () << std :: endl ; 29 } 30 31 // not allowed for virtual function w/o default implementation 32 // Shape l_shape1 (); 33 return 0; 34 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual_main.cpp Right virtual functions are called (even if the compiler doesn t have this knowledge) due to runtime decoding How is this working? vtables (no details in this course) Details of Object Orientation in C++, July 2, 2014 10 19 class Base { 20 // private : 21 public : 22 void staticprint () { 23 std :: cout << "base " << std :: endl ; } 25 26 virtual void dynamicprint () { 27 std :: cout << "base " << std :: endl ; 28 } 29 }; 1.2 Static and Dynamic Decoding code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/static_dynamic.cpp 31 class Derived : public Base { 32 // private : 33 public : 34 void staticprint () { 35 std :: cout << "derived " << std :: endl ; 36 } 37 38 virtual void dynamicprint () { 39 std :: cout << "derived " << std :: endl ; 40 } 41 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/static_dynamic.cpp Details of Object Orientation in C++, July 2, 2014 11 Static and Dynamic Decoding (2) 1.3 Virtual Destructors 43 int main () { 44 Base l_base ; 45 l_base. staticprint (); 46 l_base. dynamicprint (); 47 48 Derived l_derived ; 49 l_derived. staticprint (); 50 l_derived. dynamicprint (); 51 52 Base * l_derivedpointer = & l_derived ; 53 l_derivedpointer -> staticprint (); 54 l_derivedpointer -> dynamicprint (); 55 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/static_dynamic.cpp Right virtual functions are called (even if the compiler doesn t have this knowledge) due to runtime decoding How is this working? vtables (upcoming) 19 class Base { 20 // private : 21 public : 22 virtual ~ Base () { std :: cout << "clean up after Base " << std :: endl ; } 23 // usually bad practive : not virtual for a base class 25 //~ Base () { std :: cout << "clean up after Base " << std :: endl ; } 26 }; 27 28 class Derived : public Base { 29 // private : 30 public : 31 virtual ~ Derived () { std :: cout << "clean up after Derived " << std :: endl ; } 32 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual_destructor.cpp Details of Object Orientation in C++, July 2, 2014 12 Details of Object Orientation in C++, July 2, 2014 13 Virtual Destructors (2) 22 virtual ~ Base () { std :: cout << "clean up after Base " << std :: endl ; } 31 virtual ~ Derived () { std :: cout << "clean up after Derived " << std :: endl ; } 34 int main () { 35 Base l_base ; 36 Derived l_derived ; 37 38 Base * l_pointertobase = new Base ; 39 Derived * l_pointertoderived1 = new Derived ; 40 Base * l_pointertoderived2 = new Derived ; 41 42 delete l_pointertobase ; 43 delete l_pointertoderived1 ; 44 delete l_pointertoderived2 ; // might cause trouble 45 return 0; 46 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual_destructor.cpp Virtual destructors are bound to the type the object at creation. Details of Object Orientation in C++, July 2, 2014 14 Virtual Destructors (3) 25 //~ Base () { std :: cout << "clean up after Base " << std :: endl ; } 31 virtual ~ Derived () { std :: cout << "clean up after Derived " << std :: endl ; } 34 int main () { 35 Base l_base ; 36 Derived l_derived ; 37 38 Base * l_pointertobase = new Base ; 39 Derived * l_pointertoderived1 = new Derived ; 40 Base * l_pointertoderived2 = new Derived ; 41 42 delete l_pointertobase ; 43 delete l_pointertoderived1 ; 44 delete l_pointertoderived2 ; // might cause trouble 45 return 0; 46 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/virtual_destructor.cpp Non-virtual destructors are bound to the type of the pointer, which points to them. Details of Object Orientation in C++, July 2, 2014 15 In Detail You need a virtual destructor for an object if: A class is derived from it new is used to construct objects of your class Virtual Destructors: Summary delete is called on the resulting pointers, which have the type of a base class Rule of Thumb And much simpler: Virtual member functions Virtual destructor 1.4 Extended Access Control - Inheritance protected members can be accessed by derived classes Inheritance itself has access control Public inheritance (most commonly used) Base Derived Access Public Access public protected private Protected inheritance Base Derived Access Public Access public protected private Private inheritance: Same as protected, but derived classes can t access anymore Details of Object Orientation in C++, July 2, 2014 16 Details of Object Orientation in C++, July 2, 2014 17

Extended Access Control - friend 2 Type Conversions: Implicit Type Conversion in C 18 class Simple { 19 // private : 20 int m_private ; 21 protected : 22 int m_protected ; 23 public : int m_public ; 25 26 friend void modify ( Simple & io_simple ); 27 friend class Friend ; 28 friend class DerivedFriend ; 29 }; 30 31 void modify ( Simple & io_simple ) { 32 io_simple. m_private = 1; 33 io_simple. m_protected = 1; 34 io_simple. m_public = 1; 35 } Keyword code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/inheritance/friend.cpp friend allows functions or classes to access private and protected members Details of Object Orientation in C++, July 2, 2014 18 19 int main (){ 20 unsigned int l_uint1 = -1; 21 unsigned int l_uint2 = -2; 22 unsigned int l_uint3 = -1 + 1; 23 int l_int1 = true ; int l_bool1 = -15; 25 double * l_pointer = NULL ; 26 bool l_bool2 = l_pointer ; 27 int l_int2 = 3.9; 28 float l_float1 = 5 / 2; 29 float l_float2 = l_float1 * 0.5; // where s the implicit typecast? 43 }; Task code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/implicit.cpp What is the result of the operations above? You have five minutes.. Details of Object Orientation in C++, July 2, 2014 20 Implicit Type Conversion - Rules An expression expr of a given type is implicitly converted if used in one of the following situations: [...] Expression expr is used as an operand of an arithmetic or logical operation. Expression expr is used as a condition in an if statement or an iteration statement (such as a for loop). Expression expr will be converted to bool (or int in C). Expression expr is used in a switch statement. Expression expr will be converted to an integral type.... IBM, XL C/C++ (V6.0) Details of Object Orientation in C++, July 2, 2014 21 Implicit Type Conversion - Rules (2) Expression expr is used in an initialisation. This includes the following: An assignment is made to an lvalue that has a different type than expr. A function is provided an argument value of expr that has a different type than the parameter. Expression expr is specified in the return statement of a function, and expr has a different type from the defined return type for the function. Compiler will allow an implicit conversion of an expression expr to a type T if and only if the compiler allows the following statement: 1 T var = expr ; You can perform explicit type conversions using one of the cast operators, the function style cast, or the C-style cast. IBM, XL C/C++ (V6.0) Details of Object Orientation in C++, July 2, 2014 22 19 int main (){ 20 double l_double = 3.9; 21 C -like and Functional Type Casting 22 int l_int1 = ( int ) l_double ; // C- like 23 int l_int2 = int ( l_double ); // functional 25 std :: cout << l_double << std :: endl ; 26 std :: cout << l_int1 << std :: endl ; 27 std :: cout << l_int2 << std :: endl ; 28 29 return 0; 30 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/clike_functional.cpp C-like/functional type casting is extremely powerful (no restrictions), but also error-prone: You are circumventing type checks at compile time Details of Object Orientation in C++, July 2, 2014 23 Example Classes 19 class Base { 20 // private : 21 public : 22 virtual ~ Base () {}; 23 }; 25 class Derived : public Base { 26 // private : 27 public : 28 virtual ~ Derived () {}; 29 }; Explicit Type Conversion in C ++ C ++ adds four less error-prone type casts to your toolbox: dynamic_cast<t>(e) static_cast<t>(e) reinterpret_cast<t>(e) const_cast<t>(e), e is the expression and T the new type. Important features: Now Details of Object Orientation in C++, July 2, 2014 31 int main () { 32 Base * l_pointertoderived1 = new Derived ; 33 Base * l_pointertobase = new Base ; 34 // not allowed : implicit down cast 35 // Derived * l_pointertoderived2 = l_pointertoderived1 ; 36 // Derived * l_pointertoderived3 = l_pointertobase ; 37 38 Derived * l_pointertoderived4 = dynamic_cast <Derived * >( l_pointertoderived1 ); 39 Derived * l_pointertoderived5 = dynamic_cast <Derived * >( l_pointertobase ); 48 } Dynamic Cast code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/dynamic.cpp Works on references and pointers; Always allows for upcast (derived to base), downcasts only (base to derived), if save, else: NULL. Warning: Performance overhead due to Run-time type information (RTTI). Details of Object Orientation in C++, July 2, 2014 25 Dynamic Cast (2) 41 if( l_pointertoderived4 ) std :: cout << "first cast works " << std :: endl ; 42 else std :: cout << "first cast returns NULL " << std :: endl ; 43 44 if( l_pointertoderived5 ) std :: cout << "second cast works " << std :: endl ; 45 else std :: cout << "second cast returns NULL " << std :: endl ; 46 47 return 0; 48 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/dynamic.cpp Works on references and pointers; Always allows for upcast (derived to base), downcasts only (base to derived), if save, else: NULL. Warning: Performance overhead due to Run-Time Type Information (RTTI). Details of Object Orientation in C++, July 2, 2014 26

Static Cast Reinterpret Cast 29 int main () { 30 Base * l_pointer1 = new Base ; 31 Derived *l_pointer2 = static_cast <Derived *>( l_pointer1 ); 32 // not allowed for static casts 33 //int *l_pointer3 = static_cast <int *>( l_pointer2 ); 34 35 return 0; 36 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/static.cpp Allows pointers of related classes to be converted into each other (up- & downcasts) and all operations allowed via implicit conversions Warning: No checks done (NULL result) as in dynamic Fast but error-prone 31 int main () { 32 Base * l_pointer1 = new Base ; 33 Derived * l_pointer2 = reinterpret_cast < Derived * >( l_pointer1 ); 34 int * l_pointer3 = reinterpret_cast < int * >( l_pointer2 ); 35 36 std :: cout << reinterpret_cast <long >( l_pointer1 ) << std :: endl ; 37 std :: cout << reinterpret_cast <long >( l_pointer2 ) << std :: endl ; 38 std :: cout << reinterpret_cast <long >( l_pointer3 ) << std :: endl ; 39 40 return 0; 41 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/reinterpret.cpp Allows any pointer to be converted to any other pointer, pointer to integral type and integral type to pointer Warning: Low level binary copies are involved Fast but error-prone Details of Object Orientation in C++, July 2, 2014 27 Details of Object Orientation in C++, July 2, 2014 28 Const Cast Automatic / implicit conversions 19 void print ( int &i ) { 20 std :: cout << i << std :: endl ; 21 } 22 23 int main () { const int l_int = 27; 25 26 // not allowed : print (..) is allowed to modify l_int 27 // print ( l_int ); 28 29 print ( const_cast <int & >( l_int ) ); 30 31 return 0; 32 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/type_conversion/const.cpp Overwrites the constant status of a variables Code 46 Circle ( double i_radius ): 56 void printsurfacearea ( const Circle & circle ) { 57 std :: cout << "Surface of the circle is " << circle. getsurfacearea () << std :: endl ; 58 } 59 60 int main () { 61 Circle l_circle ( 2.3 ); 62 printsurfacearea ( l_circle ); 63 64 printsurfacearea (5.42) ; Int is implicitly converted to Shape. Can be avoided with keyword explicit! Details of Object Orientation in C++, July 2, 2014 29 Details of Object Orientation in C++, July 2, 2014 30 2.1 Operator Overloading Operator Overloading - Operators C++ supports Operator Overloading to allow for more expressive and readable code. Redefine basic operators to work on C++-objects: Operation Precedence Example: concatenate strings 9 string a(" Hello "); 10 string b(" World!"); 11 string c=a+b; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/string.cpp Operator Overloading allowed for (). ~ - * + ++ / sizeof.* ->* [] -> ::! -- % new & << >> < > <= >= == delete!= ^ &&?: += -= (type) /= *= %= <<= >>= &= ^= =, Question: What is the meaning of ->* in the context of strings or Shapes??? Use operator overloading judiciously! Prefer methods where possible! Details of Object Orientation in C++, July 2, 2014 31 Details of Object Orientation in C++, July 2, 2014 32 Example: Operator+=() on arrays 4 class IntArray { 5 int * array ; 6 7 public : 8 IntArray () { 9 array = new int [3]; 10 for ( int i = 0; i < 3; i ++) { 11 array [i] = i; 12 } 13 } Operator Overloading - Syntax code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/array.cpp As member function: 19 IntArray & operator +=( const IntArray & other ) { As global function: As member function: 19 IntArray & operator +=( const IntArray & other ) { 20 for ( int i = 0; i < 3; i ++) { 21 array [i] += other. array [i]; 22 } 23 } As global function: 32 IntArray & operator+=( IntArray & first, IntArray & second ) { 33 for ( int i = 0; i < 3; i ++) { 34 first. get (i) += second. get (i); 35 } 36 } Example The variant as global function allows to overload operators for types which are not directly accessible (e.g. std::ostream). 32 IntArray & operator+=( IntArray & first, IntArray & second ) { Details of Object Orientation in C++, July 2, 2014 33 Details of Object Orientation in C++, July 2, 2014 34

General Rules: Overloading - Some Rules Overload only when necessary: Comparison ( Standard library); Assignment Operator Make overloaded operators behave similar to the native C++-operator! E.g. have the assignment operator return a reference to this: 1 i n t a = b = c = 5; 2 MyClass a = b = c = d ; A special operator: operator=(); Not inherited Autogenerated by compiler, if it is not defined by the programmer Bit-wise assignment of object values Details of Object Orientation in C++, July 2, 2014 35 Default-Constructor (if no other Ctor defined) Desctructor (if not defined explicitely) Copy-Constructor (if not defined explicitely) Assignment Operator (if not defined explicitely) Why? Question: How to pass an object by value??? 34 void add ( const IntArray other ) { 35 for ( int i = 0; i < 3; i ++) { 36 array [i] += other. array [i]; 37 } 38 } 44 IntArray first ; 45 IntArray second ; 46 first. add ( second ); 2.2 Autogenerated Functions code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/array_assignment.cpp Details of Object Orientation in C++, July 2, 2014 36 Implicit Copy Constructor Implicit Copy Constructor (2) 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; 25 public : 26 void setvalues ( int i_a, const std :: string &i_b ) { m_a = i_a ; m_b = i_b ; }; 27 void printvalues () { std :: cout << m_a << ", " << m_b << std :: endl ; }; 28 }; 29 30 int main () { 31 SimpleClass l_simple1 ; 32 l_simple1. setvalues ( 1, " simple1 " ); 33 l_simple1. printvalues (); 34 35 // call copy constructor 36 SimpleClass l_simple2 ( l_simple1 ); 37 l_simple2. printvalues (); 38 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/copy_constructor/implicit.cpp 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; 25 public : 26 void setvalues ( int i_a, const std :: string &i_b ) { m_a = i_a ; m_b = i_b ; }; 27 void printvalues () { std :: cout << m_a << ", " << m_b << std :: endl ; }; 28 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/copy_constructor/implicit.cpp The compiler generates an implicit copy constructor, which is used when a new object is created from another and provides a member-wise copy of the source object Details of Object Orientation in C++, July 2, 2014 37 Details of Object Orientation in C++, July 2, 2014 38 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; 25 public : 26 SimpleClass () {}; 27 Explicit Copy Constructor 28 SimpleClass ( const SimpleClass & i_src ): 29 m_a ( i_src. m_a ), 30 m_b ( i_src. m_b ) { 31 std :: cout << "copy constructor called " << std :: endl ; 32 }; 35 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/copy_constructor/explicit.cpp As already seen for the constructor and destructor, a manual implementation is possible and sometimes necessary; besides the example above different signatures are possible Details of Object Orientation in C++, July 2, 2014 39 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; Implicit Assignment Operator 25 public : 26 void setvalues ( int i_a, const std :: string &i_b ) { m_a = i_a ; m_b = i_b ; }; 27 void printvalues () { std :: cout << m_a << ", " << m_b << std :: endl ; }; 28 }; 29 30 int main () { 31 SimpleClass l_simple1, l_simple2 ; 32 l_simple1. setvalues ( 1, " simple1 " ); 33 l_simple1. printvalues (); 34 35 // call the assignment operator 36 l_simple2 = l_simple1 ; 37 l_simple2. printvalues (); 38 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/assignment_operator/implicit.cpp Details of Object Orientation in C++, July 2, 2014 40 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; Implicit Assignment Operator 25 public : 26 void setvalues ( int i_a, const std :: string &i_b ) { m_a = i_a ; m_b = i_b ; }; 27 void printvalues () { std :: cout << m_a << ", " << m_b << std :: endl ; }; 28 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/assignment_operator/implicit.cpp An implicit assignment operator is generated by the compiler, which does a member-wise assignment of each source member Details of Object Orientation in C++, July 2, 2014 41 20 class SimpleClass { 21 // private : 22 int m_a ; 23 std :: string m_b ; 25 public : 26 SimpleClass () {}; 27 Explicit Assignment Operator 28 SimpleClass & operator =( const SimpleClass & i_src ) { 29 m_a = i_src. m_a ; 30 m_b = i_src. m_b ; 31 std :: cout << "assignment operator called " << std :: endl ; 32 return * this ; 33 }; 48 SimpleClass l_simple3 ( l_simple1 = l_simple2 ); code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/objects/assignment_operator/explicit.cpp Again a manual implementation is possible and sometimes required; different signatures are possible Details of Object Orientation in C++, July 2, 2014 42

Deep vs. Shallow Copy Deep vs. Shallow Copy (2) 4 class IntArray { 5 int * array ; 34 void add ( const IntArray other ) { 35 for ( int i = 0; i < 3; i ++) { 36 array [i] += other. array [i]; 37 } 38 } 43 int main ( int argc, char ** argsv ) { 44 IntArray first ; 45 IntArray second ; 46 first. add ( second ); code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/array_assignment.cpp 4 class IntArray { 5 int * array ; 34 void add ( const IntArray other ) { 35 for ( int i = 0; i < 3; i ++) { 36 array [i] += other. array [i]; 37 } 38 } 43 int main ( int argc, char ** argsv ) { 44 IntArray first ; 45 IntArray second ; 46 first. add ( second ); code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/array_assignment.cpp Auto-generated copy-constructor and assignment-operator: perform bitwise copy invoke copy-ctor / assignment operator on member variables. This works fine as long as no pointers are involved! Details of Object Orientation in C++, July 2, 2014 43 A bitwise copy (shallow copy) creates two pointers to the same memory region! The same memory region will be free d multiple times! Details of Object Orientation in C++, July 2, 2014 44 4 class IntArray { 5 int * array ; 15 IntArray ( const IntArray & other ) { 16 array = new int [3]; 17 for ( int i = 0; i < 3; i ++) { 18 array [i] = other. array [i]; 19 } 20 } 34 void add ( const IntArray other ) { 35 for ( int i = 0; i < 3; i ++) { 36 array [i] += other. array [i]; 37 } 38 } 43 int main ( int argc, char ** argsv ) { 44 IntArray first ; 45 IntArray second ; 46 first. add ( second ); Deep vs. Shallow Copy (3) code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/operator_overloading/array_assignment.cpp Solution: Perform a deep copy in the copy constructor! Details of Object Orientation in C++, July 2, 2014 45 Overview IO-streams: One major advantage of C ++ over pure C and Fortran 3 Streams Intuitive and flexible I/O: User interacts with the stream only, not the underlying implementation, i.e. communication with a printer Extraction operator >>: Read values from stream Insertion operator <<: Write values to stream <iostream>: Standard input & output stream objects, part of the C ++ Standard Library; Objects: cin: Input cout: Output cerr: Error (unbuffered) clog: Log (buffered) Custom implementation possible with overloading Details of Object Orientation in C++, July 2, 2014 47 Hello Streams 20 int main () { 21 // print a welcome message and ask for input 22 std :: cout << "Welcome to hello_world." << std :: endl 23 << "Please enter some input :" << std :: endl ; 25 // user input 26 std :: string l_userinput ; 27 28 // get the input of the user 29 std :: cin >> l_userinput ; 30 Streams: Hello World 31 if( l_userinput == " error " ) { // print to standard error stream 32 std :: cerr << "This is the error stream." << std :: endl ; 33 } 34 else { // print user input to standard output stream 35 std :: cout << "You entered : " << l_userinput << std :: endl ; 36 } 37 38 return 0; 39 } Details of Object Orientation in C++, July 2, 2014 48 47 int main () { 48 char l_chars [4]; 52 std ::cin >> std :: setw (4) >> l_chars ; 57 double l_floatnumber = 1.0 / 7.0; 58 int l_intnumber = 165; 59 Streams: Default Manipulators 60 // different predefined stream manipulators 61 std :: cout << "precision 3: " 62 << std :: setprecision (3) << l_floatnumber 63 << std :: endl << "precision 20: " 64 << std :: setprecision (20) << l_floatnumber 65 << std :: endl << "hexadecimal : " 66 << std ::hex << std :: showbase << l_intnumber 67 << std :: endl ; 73 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/beyond_c++98/io/streams/manipulate.cpp Different predefined stream manipulators exist; precision & number format for example Details of Object Orientation in C++, July 2, 2014 49 class Tabber { Streams: Custom Manipulators 37 friend std :: ostream & operator <<( std :: ostream &io_stream, const Tabber & i_tabber ) { 38 // loop over the number of repeats 39 for ( unsigned l_repeat = 0; l_repeat < i_tabber. m_numberofrepeats ; l_repeat ++ ) { 40 io_stream << "\t"; 41 } 42 43 return io_stream ; 44 } 45 }; 70 std :: cout << "tab insertion test : " << Tabber (3) << "done.." << std :: endl ; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/beyond_c++98/io/streams/manipulate.cpp Operator overloading of << and >> allows for custom implementations Details of Object Orientation in C++, July 2, 2014 50 File I/O is handled similar to std::cin / std::cout. File streams are defined in header fstream. ofstream: file stream to write to 4 int main ( int argc, char ** argsv ) { 5 File Streams 6 std :: ofstream out ; 7 out.open ("test.txt ", std :: ios_base ::app ); 8 if (! out. good () ) { 9 std :: cerr << "Could not open file test.txt!" << std :: endl ; 10 return -1; 11 } 12 13 14 for ( int i = 0; i < 100; i ++) { 15 out << i << " " << std :: endl ; 16 } Details of Object Orientation in C++, July 2, 2014 51

File Streams (2) File I/O is handled similar to std::cin / std::cout. File streams are defined in header fstream. ifstream: file stream to read from File open modii: File Streams (3) ios_base::in ios_base::out ios_base::app ios_base::ate ios_base::binary ios_base::trunc 4 5 int main ( int argc, char ** argsv ) { 6 7 std :: ifstream in; 8 in.open ("test.txt ", std :: ios_base ::in); 9 if (! in. good () ) { 10 std :: cerr << "Could not open file test.txt!" << std :: endl ; 11 return -1; 12 } 13 14 int read = 0; 15 while (! in.eof ()) { 16 in >> read ; 17 std :: cout << " read number " << read << " "; 18 } These modii can be combined with logical or. Function getline: read file line-by-line: 15 char line [200]; 16 while (in. good ()) { 17 in. getline (line,200) ; 18 std :: cout << " read line " << line << " " << std :: endl ; 19 } A char-array can be used as source for a stringstream, which allows for formatted input again! Details of Object Orientation in C++, July 2, 2014 52 Details of Object Orientation in C++, July 2, 2014 53 Additional Structure Performance: Overhead One vtable per class (not per object of the type); contains a function pointer for every virtual function this class can call Critical for a large number of classes in the program; Bad software design? One vpointer per object containing virtual function Crititcal for small objects; AoS vs. SoA? Fetch-fetch-call: Follow two pointers instead of one Crtical for virtual functions with minor workloads In General Vtables come with a certain overhead but bring functionality. Low-level implementations come with an overhead of their own (i.e. if-else statements) to support same functionality Use inheritance/vtables if reasonable for your software design t.b.d. Performance: Inlining Details of Object Orientation in C++, July 2, 2014 55 Details of Object Orientation in C++, July 2, 2014 56

1 Repetition: DVDRentalService Object-oriented Programming in C++ Templates & Standard Template Library (STL) Wolfgang Eckhardt, Tobias Neckel July 3, 2014 Cross-check solution of problem concerning DVDRentalService of Worksheet 3! Templates & Standard Template Library (STL), July 3, 2014 1 Templates & Standard Template Library (STL), July 3, 2014 3 2 Headers and Forward Declarations DVDRental Extended Store for an actor the DVDs he/she is involved in: 2 # ifndef ACTOR_H_ 3 # define ACTOR_H_ 4 5 # include " DVD.h" 6 # include <string > 7 8 class Actor { 9 10 private : 11 std :: string name ; 12 13 int numdvds ; 14 15 DVD * dvds [5]; 2 # ifndef DVD_H_ 3 # define DVD_H_ 4 5 # include " Actor.h" 6 # include <string > 7 8 class DVD { 9 10 private : 11 std :: string title ; 12 13 int numactors ; 14 15 Actor * actors [5]; g++ -c DVD.cpp: In file included from DVD.h:5:0, from DVD.cpp:2: Actor.h:15:2: error: DVD does not name a type Headers and Forward Declarations DVDRental Extended (2) Problem: Circular inclusion in header files. The second header will not be included any more due to the include guard, thus the second class definition in incomplete. Resolution: For pointer and reference members, a full class definition is not required. Use a forward-declaration instead! 5 # include " DVD.h" 6 # include <string > 7 8 class Actor { 9 10 private : 11 std :: string name ; 12 13 int numdvds ; 14 15 DVD * dvds [5]; 5 # include <string > 6 7 class DVD ; 8 9 class Actor { 10 11 private : 12 std :: string name ; 13 14 int numdvds ; Templates & Standard Template Library (STL), July 3, 2014 5 Templates & Standard Template Library (STL), July 3, 2014 6 Headers and Forward Declarations DVDRental Extended (3) Problem: Circular inclusion in header files. The second header will not be included any more due to the include guard, thus the second class definition in incomplete. Resolution: For pointer and reference members, a full class definition is not required. Use a forward-declaration instead! Include header of declared class in implementation file! Task 3.1 Motivation for Templates: Sorting Given: Generic algorithm, which sorts objects Goal: Apply this algorithm to all objects, which are sortable One and only requirement: Operator < is implemented for the objects Sketch Best practises: Always try to use forward declarations instead of #include<> Try to use #include<> only in implementation files reduced compilation time (header processing, dependencies) Collection of Objects Sorting Algorithm Sorted Collection of Objects Templates & Standard Template Library (STL), July 3, 2014 7 Templates & Standard Template Library (STL), July 3, 2014 9 What options do we have so far? Collection of Integers Collection of Penguins Collection of Bikes I-Sorting Algorithm P-Sorting Algorithm B-Sorting Algorithm Option: Copy & Paste Sorted Collection of Integers Sorted Collection of Penguins Sorted Collection of Bikes Copy & paste the implementation for all kind of types, which we might want to compare; obviously not a smart choice Templates & Standard Template Library (STL), July 3, 2014 10 #if TYPE==1 typedef int PARAMETER; #elif TYPE==2 typedef Penguin PARAMETER; #elif TYPE==3 typedef Bike PARAMETER; #else #error TYPE not supported #endif What options do we have so far? Define a preprocessor macro, which takes care about the object-types; works but error-prone ( ) Option: Macros Templates & Standard Template Library (STL), July 3, 2014 11

Option: Inheritance Option: Templates What options do we have so far? What are we going learn about? Sortable virtual ~Sortable(); C++ virtual Sortable& operator<(sortable &i_first, Sortable &i_second) const = 0; Collection of S-Objects Sorting Algorithm Sorted Collection of S-Objects Collection of Objects Sorting Algorithm Sorted Collection of Objects Integer Penguin Bike Machine Code Interface Sortable with pure virtual member function operator< Implementation of operator< in every inehrited class Drawbacks No typesafety checks at compile time comparison of bikes and penguins Each object for our algorithm needs to implement Sortable Overhead coming with vtables Collection of Integers Collection of Penguins Collection of Bikes I-Sorting Algorithm P-Sorting Algorithm B-Sorting Algorithm Sorted Collection of Integers Sorted Collection of Penguins Sorted Collection of Bikes Templates & Standard Template Library (STL), July 3, 2014 12 Templates & Standard Template Library (STL), July 3, 2014 13 What are we going learn about? Option: Templates (2) Function and class templates define a generic layout for functions and classes Based on template parameters: compiler decides on instances (template classes) of a function/class to be generated With some simplifications: Compiler supported copy & paste Pros: High-level code provides a single implementation of the one very same algorithm Compiler generated code provides implementations for all used parametrizations of our template Magic happens at compile time no performance overhead checks for typesafety Cons: less readable code & cryptic compile errors Templates & Standard Template Library (STL), July 3, 2014 14 3.2 Function Templates: Basics Assume that we want to implement a generic Algorithm : 23 int addint ( int i_first, int i_second ) { return i_first + i_second ; 25 } 26 27 double adddouble ( double i_first, double i_second ) { 28 return i_first + i_second ; 29 } 38 int main (){ 39 std :: cout << addint ( 3, 5 ) << std :: endl ; 40 std :: cout << adddouble ( 3.0, 5.0 ) << std :: endl ; 46 return 0; 47 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/functions/basics.cpp Naive Approach Copy & paste Code duplication Templates & Standard Template Library (STL), July 3, 2014 15 Function Templates: Basics (2) Keyword template together with angle bracket notation < [...] > declares a function template Template parameter of the template parameter list (between angle brackets) is used like a normal object type inside the function Add compile time the compiler decides which template functions have to be generated ( automated copy & paste ) 34 template < class T > T add ( T i_first, T i_second ) { 35 return i_first + i_second ; 36 } 42 std :: cout << add ( 3, 5 ) << std :: endl ; 43 std :: cout << add ( 3.0, 5.0 ) << std :: endl ; 44 std :: cout << add ( std :: string ( "3" ), 45 std :: string ( "5" ) ) << std :: endl ; 46 return 0; 47 }; 20 class Custom { 21 public : 22 Custom ( int i ) {}; 23 }; Template Functions: Requirements 25 template < class T > T add ( T i_first, T i_second ) { 26 T l_result ; 27 l_result = i_first + i_second ; 28 29 return l_result ; 30 } 31 32 int main (){ 33 std :: cout << add ( 3, 5 ) << std :: endl ; 34 std :: cout << add ( 3.0, 5.0 ) << std :: endl ; 35 std :: cout << add ( std :: string ( "3" ), 36 std :: string ( "5" ) ) << std :: endl ; 37 38 Custom l_custom1 (1), l_custom2 (2) ; 39 // add ( l_custom1, l_custom2 ); not allowed 40 41 return 0; 42 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/functions/basics.cpp Templates & Standard Template Library (STL), July 3, 2014 16 Templates & Standard Template Library (STL), July 3, 2014 17 Template Functions: Requirements (2) Derived template function needs to fulfill all requirements of the function template (like every non-template func.); here: Default constructor T::T() Implementation of operator+ 25 template < class T > T add ( T i_first, T i_second ) { 26 T l_result ; 27 l_result = i_first + i_second ; 28 29 return l_result ; 30 } 31 32 int main (){ 38 Custom l_custom1 (1), l_custom2 (2) ; 39 // add ( l_custom1, l_custom2 ); not allowed 40 41 return 0; 42 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/functions/requirements.cpp Templates & Standard Template Library (STL), July 3, 2014 18 Function Templates: Mixing Arguments Template and non-template parameters can be mixed: Only required types should be generic 19 template < class T > T product ( T * i_values, int i_size ) { 20 T l_result = i_values [0]; 21 22 for ( int l_entry = 1; l_entry < i_size ; l_entry ++ ) { 23 l_result *= i_values [ l_entry ]; } 25 26 return l_result ; 27 } 28 29 int main (){ 30 double l_array [5] = { -1.5, 1.4, 5.2, -6.1, 2.9}; 31 32 std :: cout << product (l_array, 5) << std :: endl ; 33 std :: cout << product (l_array, 5.2) << std :: endl ; // implicit cast to int 34 35 return 0; 36 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/functions/mixing.cpp Templates & Standard Template Library (STL), July 3, 2014 19

Function Templates: Multiple Parameters Template parameter list can contain multiple template parameters Type sepcific template functions can explicitly called 19 template < class T1, class T2 > void print ( T1 i_value1, T2 i_value2, int i_repeats ) { 20 for ( int l_repeat = 0; l_repeat < i_repeats ; l_repeat ++ ) { 21 std :: cout << i_value1 << std :: endl ; 22 std :: cout << i_value2 << std :: endl ; 23 } } 25 26 int main (){ 27 print ( 5.0, 1, 5 ); 28 print ( long (2), 1.2f, 2 ); 29 print ( a, b, 27.3 ); // typecast : non - template arg. 30 print < double, int >( a, b, 27.3 ); // typecast : (non -) template args. 31 32 return 0; 33 }; Templates & Standard Template Library (STL), July 3, 2014 20 Assume that we want to implement a generic class: 22 class PairDouble { 23 // private : double m_firstvalue ; 25 double m_secondvalue ; 26 27 public : 28 PairDouble ( double i_first, double i_second ): 29 m_firstvalue ( i_first ), 30 m_secondvalue ( i_second ) {}; 31 }; 32 33 class PairInt { 34 // private : 35 int m_firstvalue ; 36 int m_secondvalue ; 37 38 public : 39 PairInt ( int i_first, int i_second ): 40 m_firstvalue ( i_first ), 41 m_secondvalue ( i_second ) {}; 42 }; 3.3 Class Templates: Basics Naive Approach: Copy & paste Code duplication Templates & Standard Template Library (STL), July 3, 2014 21 Class Templates: Basics (2) Keyword template together with angle bracket notation < [...] > declares a class template Template parameter of the template parameter list (between angle brackets) is used like a normal object type inside the class At compile time, the compiler decides which template classes have to be generated ( automated copy & paste ) 47 template < class T > class Pair { 48 // private : 49 T m_firstvalue ; 50 T m_secondvalue ; 51 52 public : 53 Pair ( T i_first, T i_second ): 54 m_firstvalue ( i_first ), 55 m_secondvalue ( i_second ) {}; 56 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/class/basics.cpp Templates & Standard Template Library (STL), July 3, 2014 22 Class Templates: Basics (3) At compile time the decision is made, which template classes are generated; Here: Pair<double> Pair<int> Pair<long> In contrast to usage of function templates: Template parameters are required for template classes 58 int main (){ 59 Pair < double > l_pairdouble ( 5.1, 2.3 ); 60 Pair < int > l_pairint1 ( 2, 1 ); 61 Pair < int > l_pairint2 ( 3, 4 ); 62 Pair < long > l_pairlong ( 1, 2 ); 74 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/class/basics.cpp Templates & Standard Template Library (STL), July 3, 2014 23 Class Templates: Basics (4) Template classes behave like regular classes No copy-constructor, assignment-operator,.. is generated for different template classes (even if implicit conversion of template parameters exists!) 58 int main (){ 64 l_pairint2 = l_pairint1 ; 65 66 // not allowed : template parameter missing 67 // Pair ( 1, 2 ); 68 69 // not allowed : different template classes 70 // l_pairlong = l_pairint1 ; 71 // Pair <long > l_pairlong2 ( l_pairint1 ); 72 73 return 0; 74 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/class/basics.cpp Templates & Standard Template Library (STL), July 3, 2014 Multiple and Non-Type Parameters 19 template < class T1, class T2, int SIZE > class SoA { 20 public : 21 const int m_size ; 22 23 T1 m_firstarray [ SIZE ]; T2 m_secondarray [ SIZE ]; 25 26 SoA (): m_size ( SIZE ) {}; 27 28 void print () { 29 for ( int l_i = 0; l_i < SIZE ; l_i ++ ) { 30 std :: cout << m_firstarray [l_i ] << std :: endl ; 31 std :: cout << m_secondarray [l_i ] << std :: endl ; 32 } 33 } 34 }; code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/class/multiple.cpp Class template parameter list can contain one or more of: type non-type (but value) templates (upcoming) Templates & Standard Template Library (STL), July 3, 2014 25 Multiple and Non-Type Parameters (2) Class template parameter list can contain one or more of: type non-type (but value) templates (upcoming) 36 int main (){ 37 SoA<double, long, 10> l_soa ; 38 39 for ( int l_i = 0; l_i < l_soa. m_size ; l_i ++ ) { 40 l_soa.m_firstarray [l_i ] = 1.0/( l_i +1) ; 41 l_soa. m_secondarray [ l_i ] = l_i * l_i ; 42 } 43 44 l_soa. print (); 45 46 return 0; 47 }; Performance is the same as for specialized non-template functions/classes Compiler errors/warnings are distributed accross to phase lookup; code problems might appear in a very late state Heavy templatized codes tend to have a very long compilation phase and very large error output (rumors of 10MB single line output for popular codes exist) Impact code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/templates/class/multiple.cpp Templates & Standard Template Library (STL), July 3, 2014 26 Templates & Standard Template Library (STL), July 3, 2014 27

4 Standard Template Library (STL) Survey of STL - html://www.cppreference.com STD STL containers iterators algorithms C++ library of container classes, algorithms and iterators Generic library heavily based on templates Small in comparison to other languages (Java, Python); Large in comparison to C Growing with each new standard (esp C++11) Additionally: Boost libraries (http://www.boost.org/) as test field for extensions Templates & Standard Template Library (STL), July 3, 2014 29 Templates & Standard Template Library (STL), July 3, 2014 30 4.1 STL Containers - Example: std::vector Vector implements a dynamic array (grows automatically with input): 2 # include <vector > 3 4 int main () { 5 std :: vector <int> numbers ; 6 7 for ( int i = 0; i < 5; i ++) { 8 numbers. push_back (i*i); 9 std :: cout << "Capacity = " << numbers.capacity () << ", size = " << numbers. size () << std :: endl ; 10 } 11 12 for ( int i =0; i < 5; i ++) { 13 std :: cout << numbers [i] << std :: endl ; 14 } 15 return 0; 16 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/stl/vector.cpp Example: std::vector (2) The type T must meet the requirements of CopyAssignable and CopyConstructible. Selected methods: empty() capacity size() clear() at() operator[ ]() push back() begin() end() true if vector is empty the size of the internal memory number of elements stored remove content element access with bounds checking element access without bounds checking add element at end return iterator to the beginning return iterator to the end Like all STL-container classes, vector supports iterators. Templates & Standard Template Library (STL), July 3, 2014 31 Templates & Standard Template Library (STL), July 3, 2014 32 Iterators STL Iterators allow to traverse a set of elements without knowledge of the implementation of the underlying set. can be used to denote ranges. 7 vector <int> numbers ; 14 for (vector <int >:: iterator it = numbers.begin (); 15 it!= numbers. end (); it ++) { 16 std :: cout << *it << std :: endl ; 17 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/stl/vector-iterator.cpp List implements a doubly-linked list: Fast insertion of new elements No random access of elements Especially useful as a FIFO or LIFO data structure 2 # include <list > 3 4 using namespace std ; 5 6 int main () { 7 list <int> numbers ; 8 9 for ( int i = 0; i < 5; i ++) { 10 numbers. push_back (i*i); Example: std::list 11 std :: cout << " size = " << numbers.size () << std :: endl ; 12 } 13 14 for (list <int >:: iterator it = numbers.begin (); 15 it!= numbers. end (); it ++) { 16 std :: cout << *it << std :: endl ; 17 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/stl/list-iterator.cpp Templates & Standard Template Library (STL), July 3, 2014 33 Templates & Standard Template Library (STL), July 3, 2014 34 Further data structures 4.2 STL Algorithms std::set std::map std::unordered set (C++11) std::unordered map (C++11) store unique objects, sorted (based on trees) store unique objects using a key, sorted (based on trees) implementation of a hash set implemementation of a hash map A number of common algorithms working on STL Containers and usual arrays: Note: Each data structure has different characteristics concerning insertion / deletion / search / sorting of objects contained! http://en.cppreference.com/w/ Templates & Standard Template Library (STL), July 3, 2014 35 Templates & Standard Template Library (STL), July 3, 2014 36