Object-oriented Programming in C++

Similar documents
Object-oriented Programming in C++

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

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

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

4. Functions. March 10, 2010

5. Applicative Programming. 1. Juli 2011

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Fast Introduction to Object Oriented Programming and C++

Absolute C++ Walter Savitch

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

CE221 Programming in C++ Part 1 Introduction

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

Operator overloading

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

CSCI 171 Chapter Outlines

Introduction to Programming using C++

10. Object-oriented Programming. 7. Juli 2011

III. Classes (Chap. 3)

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

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

PIC 10A Objects/Classes

Come and join us at WebLyceum

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

Chapter 2: Basic Elements of C++

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.

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

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Problem Solving with C++

Lab # 02. Basic Elements of C++ _ Part1

Outline. 1 About the course

EL6483: Brief Overview of C Programming Language

These are notes for the third lecture; if statements and loops.

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

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

Scientific Computing

C++ Programming: From Problem Analysis to Program Design, Third Edition

CS201 Some Important Definitions

Chapter 1 Getting Started

377 Student Guide to C++

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:

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

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

Object-Oriented Programming for Scientific Computing

CS 376b Computer Vision

Interview Questions of C++

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

CS3157: Advanced Programming. Outline

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 2 Basic Elements of C++

Objectives. In this chapter, you will:

Chapter 2. Procedural Programming

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

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

Pointers and References

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

CS201 Latest Solved MCQs

QUIZ. What are 3 differences between C and C++ const variables?

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

Introduction to C ++

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

C++ Programming for Non-C Programmers. Supplement

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

Instantiation of Template class

CSE 303: Concepts and Tools for Software Development

C++ Programming Lecture 1 Software Engineering Group

6.096 Introduction to C++ January (IAP) 2009

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

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:

C++ Support Classes (Data and Variables)

8. Object-oriented Programming. June 15, 2010

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

G52CPP C++ Programming Lecture 20

Programming, numerics and optimization

Chapter 1 INTRODUCTION

Computer Science II Lecture 1 Introduction and Background

Object Oriented Software Design II

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

A brief introduction to C++

Introduction to C++ Systems Programming

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

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

AN OVERVIEW OF C++ 1

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

Maciej Sobieraj. Lecture 1

Final CSE 131B Spring 2004

Getting started with C++ (Part 2)

COMP322 - Introduction to C++

Computer Science II Lecture 2 Strings, Vectors and Recursion

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

A SHORT COURSE ON C++

C++ For Science and Engineering Lecture 12

C++ basics Getting started with, and Data Types.

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

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Transcription:

Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel June 30, 2014 Working with C and C++, June 30, 2014 1

Challenges of This Course 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 2

What Will be Covered in This Course... Working with C and C++, June 30, 2014 3

Outline of Day 1 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... Working with C and C++, June 30, 2014 4

Outline of Day 2 & 3 Object-oriented Programming Concepts/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 Working with C and C++, June 30, 2014 5

Outline of Day 4 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 6

What Will NOT be Covered in 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. Working with C and C++, June 30, 2014 7

Organisation of This Course 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 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 as in FORTRAN, source code needs to be compiled: source: http://pages.towson.edu/davani/cosc236/handouts/com-process.html Working with C and C++, June 30, 2014 11

Comments in C / C ++ 1 // one line comment 3 /* 4 several lines 5 */ 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 12

A First Example 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 Working with C and C++, June 30, 2014 13

Basic Compilation 1 g++ -O3 -g first_example. cpp -o test_executable Working with C and C++, June 30, 2014 14

1.2 Header Files C/C++ distinguishes declaration and definition. Declaration: Tell the compiler what names are available. Definition: Define where the name is stored. Working with C and C++, June 30, 2014 15

A Second Example: More Than One File 13 # include <iostream > 14 # include " computations.h" 15 16 int main () { 17 std :: cout << " adding via function : 5+11= " << add_values (5,11) << std :: endl ; 18 return 0; 19 } code: http://www5.in.tum.de/lehre/vorlesungen/progcourse/c++/grs_2014/src/basic_usage/second_example.cpp 1 /** 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 16

Compilation of Two 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 Working with C and C++, June 30, 2014 17

Naming Conventions for Files type C C ++ implementation.c.cpp.cxx.c.cc header.h.h.hpp.hxx 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 Working with C and C++, June 30, 2014 21

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 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 24

Syntax vs. Semantics 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! Working with C and C++, June 30, 2014 25

3.1 Built-in Data Types 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 26

Built-in Data Types - int 20 int i; 21 int k; 22 i = 5; 23 k = -1; 24 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! Working with C and C++, June 30, 2014 27

Built-in Data Types - double 30 double a; 31 double b; 32 double c; 33 a = 0.145e -07; 34 b = 23.24 e09 ; 35 c = a+b; 36 std :: cout << c << std :: endl ; Working with C and C++, June 30, 2014 28

Built-in Data Types - float 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) Working with C and C++, June 30, 2014 29

Built-in Data Types - char 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 30

Built-in Data Types - bool no real boolean data type in C actually, int is (mis-)used different historic workarounds but: boolean data type in C ++ (true or false) Working with C and C++, June 30, 2014 31

Built-in Data Types & Memory Memory int x; char y; float z; 21: y // one byte 22; z // four bytes 23; 24; 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 32

Constants 1 i n t ConstantA = 1; 2 double ConstantB = 0. 4 ; 3 double ConstantC = 23.232323; 4 5 void main ( ) { 6... 7 } 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. Working with C and C++, June 30, 2014 33

3.2 Memory Organisation (WIN style) Static and global variables (Some) Read-only variables Constants (not user accessible) Code Heap Stack Appl 1 Appl 2 Reserved by OS (adrs $0, typically 128 kb) Working with C and C++, June 30, 2014 34

Memory Organisation for Variables 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. Working with C and C++, June 30, 2014 35

3.3 Type Inference double float int unsigned int Note: casts from supersets to subsets: eventually compiler warnings! Working with C and C++, June 30, 2014 36

Type Inference - Example 1 15 # include <iostream > 16 17 int main () { 18 19 // Example 1 20 unsigned int u = 2; 21 int i = 1; 22 double d; 23 24 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 ; 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

Type Inference - Example 2 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 Working with C and C++, June 30, 2014 38

Type Inference - Type Conversion Pitfall 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 Working with C and C++, June 30, 2014 39

3.4 Recap: Scopes, Loops & Branches 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 40

Recap: Loops Loops render the programming style applicative programming. Types of loops: while, do-while, for. Concept: 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 ) ; Working with C and C++, June 30, 2014 41

Recap: The For Loop 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 42

What do These Snippets Do? 20 for ( int a=0; a <20; a++) { 21 // something intelligent 22 } 23 24 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 } Working with C and C++, June 30, 2014 43

Recap: Branches if-then-else constructs: 20 double a =2.5; 21 double b =3.8; 22 23 double max ; 24 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 44

Recap: Branches (2) 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 } 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

3.5 Functions Syntax of function definitions: 1 r e t u r n t y p e 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. Working with C and C++, June 30, 2014 46

Functions - Examples 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 ) { 24 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 } 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 24 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 } 24 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 } 24 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 24 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. Working with C and C++, June 30, 2014 53

The Return Statement and Call-by-value 15 # include <iostream > 16 17 int multiplybytwo ( int x) { 18 x = x *2; 19 return x; 20 } 21 22 23 int main () { 24 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 54

const Modifier 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. Working with C and C++, June 30, 2014 55

3.7 Signature of a Function 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 56

Overloading 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! Working with C and C++, June 30, 2014 57

3.8 Pointers Memory 21: 22; 20 // int a 23; 24; 25; 26; 27; 28: The memory is enumerated using an integer. 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 o f an i n t 4 i n t * p ; Working with C and C++, June 30, 2014 58

Pointers and Addresses 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; 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

Pointers and the Memory Memory 21: 22; 20 // int a 23; 24; 22 // pointer p 25; 26; 27; 28: int a; a = 20; int *p; p = &a; a++; p++; (*p)++; *p++; // try this at home Working with C and C++, June 30, 2014 60

When to Use Pointers 1 void foo ( i n t * a ) { 2 ( * a ) ++; 3... 4 a++; / / That could not have happened w i t h 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. Working with C and C++, June 30, 2014 61

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. 24 */ 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 62

Array Declaration Memory 21: 22; // grade[0] 23; // grade[1] 24; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 1 double grade [ 4 ] ; 2 3... Working with C and C++, June 30, 2014 63

Array Access 1 double grade [ 4 ] ; Memory 21: 22; // grade[0] 23; // grade[1] 24; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 2 3... 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 64

Arrays & Pointers 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! Working with C and C++, June 30, 2014 65

Dot Product Revisited We need a range variable 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 66

Dynamic Arrays ( C ++ Style) 1 double * grades = new double [ 4 5 ] ; 2 3 d e l e t e [ ] grades ; We can create arrays on the heap. Size might be a variable, too. 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 24 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) Working with C and C++, June 30, 2014 71

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_ 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 files. It is very difficult to distinguish between these names, i.e. we 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 24 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 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

4.3 Using C Libraries in C ++ 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 # i n c l u d e <math. h> => # i n c l u d e <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

4.4Backup some stuff that may be interesting but is not covered in the lecture Working with C and C++, June 30, 2014 79

Default Arguments of Functions 1 void foo ( i n t a=3) ; 2 void bar ( ) ; 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 80

Pointer Syntax The pointer operator binds to the right neighbour. 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

Pointers and Scopes 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 ) { 24 //... 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

Pitfalls 19 int gradesbsc, gradesmsc [5]; 20 21 gradesmsc [5] = 2.3; 22 gradesmsc [3]++; 23 int * p0 = gradesmsc ; 24 int * p1 = & gradesmsc [0]; 25 int * p2 = & gradesmsc [1]; 26 gradesmsc ++; // does not work 27 p2 ++; // arrrgh 28 29 return 0; 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