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

Size: px
Start display at page:

Download "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"

Transcription

1 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, Working with C and C++, June 30, What Will be Covered in This Course Working with C and C++, June 30, 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, 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, Working with C and C++, June 30, 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: Object-oriented_Programming_wC%2B%2B_GRS-_2014 Examples used on the slides: lehre/vorlesungen/progcourse/c++/grs_2014/src/ Working with C and C++, June 30, Working with C and C++, June 30,

2 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, Basic Usage Working with C and C++, June 30, 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: 7 /** 8 * several lines, autodocutool syntax : 9 * 10 * This file is part of the C++ course. 11 Tobias Neckel, Wolfgang Eckhardt 12 * 13 LICENSE 14 * Copyright (c) * 16 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, Working with C and C++, June 30, A First Example Basic Compilation 13 # include <iostream > 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: 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, Working with C and C++, June 30, 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 int main () { 17 std :: cout << "adding via function : 5+11= " << add_values (5,11) << std :: endl ; 18 return 0; 19 } 1 /** code: 2 * Here comes some documentation : 3 * Adding two integers and returns the result. 4 */ 5 int add_values ( int a, int b); code: 1 # include " computations.h" 2 3 int add_values ( int a, int b) { 4 return a+b; 5 } code: Working with C and C++, June 30, Working with C and C++, June 30,

3 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, Working with C and C++, June 30, 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: +/GRS_2014/src/basic_usage/include_guards.h Working with C and C++, June 30, 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, 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, Working with C and C++, June 30, 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, Basics of C Working with C and C++, June 30, 2014

4 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, Working with C and C++, June 30, 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, Working with C and C++, June 30, 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 = ; 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 ; 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, Working with C and C++, June 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, Working with C and C++, June 30,

5 Constants 3.2 Memory Organisation (WIN style) 1 i n t ConstantA = 1; 2 double ConstantB = 0. 4 ; 3 double ConstantC = ; 4 5 void main ( ) { } 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, Working with C and C++, June 30, 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, Working with C and C++, June 30, Type Inference - Example 1 Type Inference - Example 2 15 # include <iostream > int main () { // Example 1 20 unsigned int u = 2; 21 int i = 1; 22 double d; 23 d = (u *10) ; 25 std :: cout << "d(wu) = " << d << std :: endl ; 26 d = (i *10 + u) ; 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; std :: cout << "c1 = " << c1 << std :: endl ; 37 c1 = 7.0; 38 std :: cout << "c1 = " << c1 << std :: endl ; double a2 = 3.0; 41 int b2 = 4; 42 int c2 = a2 + b2; std :: cout << "c2 = " << c2 << std :: endl ; code: code: Working with C and C++, June 30, Working with C and C++, June 30, Type Inference - Type Conversion Pitfall 3.4 Recap: Scopes, Loops & Branches 47 double d0 = 4 / 3; 48 std :: cout << "d0 = " << d0 << std :: endl ; double d1 = 4.0 / 3.0; 51 std :: cout << "d1 = " << d1 << std :: endl ; double d2 = 4.0 / 3; 54 std :: cout << "d2 = " << d2 << std :: endl ; code: 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, Working with C and C++, June 30,

6 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, Working with C and C++, June 30, 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 } for ( int a =1; a <20; a *=2) { 30 // something intelligent 31 } 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; double max ; if (a < b) { 25 max = b; 26 } 27 else { 28 max = a; 29 } code: comparison operators: <, >, <=, >=, ==,!= logical operators:!, &&, Working with C and C++, June 30, Working with C and C++, June 30, Recap: Branches (2) 3.5 Functions switch statement: 33 char c; 34 std :: cout << "please type a character :" << std :: endl ; 35 std :: cin >> c; 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: Attention: do not forget the break statement! Working with C and C++, June 30, Working with C and C++, June 30, 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 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: Working with C and C++, June 30, 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 } void foo2 ( double a, double h) { 28 // return 1; // error 30 } Return Statements code: 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,

7 17 int sign ( int a) { 18 // return sign 19 } 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) ; return 0; 31 } What is the main Function? code: 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, int sign ( int a) { 18 // return sign 19 } 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) ; return 0; 31 } Functions Some Best Practices code: 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, 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, # include <iostream > void foo ( int x) { 18 // do something with x 19 x = 50; 20 std :: cout << "foo (): x = " << x << std :: endl ; 21 } int main () { int x = 10; 27 foo (x); 28 std :: cout << "main (): x = " << x << std :: endl ; return 0; 31 } Call-by-value code: 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, 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 > int multiplybytwo ( int x) { 18 x = x *2; 19 return x; 20 } 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 ; x = multiplybytwo (x); 31 std :: cout << "main (): x = " << x << std :: endl ; return 0; 34 } code: 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, Working with C and C++, June 30, 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 ) { } 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, Working with C and C++, June 30,

8 1 i n t foo ( ) 2 i n t foo ( i n t a ) {} 3 i n t foo ( double a ) {} 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, Working with C and C++, June 30, Pointers and Addresses Pointers and the Memory The * operator declares a pointer. 19 int a = 20; 20 int *p; code: The & operator returns the address of a variable (address operator or reference operator). 22 p = &a; code: 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: Working with C and C++, June 30, Working with C and C++, June 30, 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 double x; 18 double y; // /** 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: 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, Working with C and C++, June 30, Array Declaration Array Access 1 double grade [ 4 ] ; Memory Memory : 22; // grade[0] 23; // grade[1] ; // grade[2] 25; // grade[3] 26; 27; 28: 22 // grade (pointer) 1 double grade [ 4 ] ; : 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, Working with C and C++, June 30,

9 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, Working with C and C++, June 30, 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, 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: 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, 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, 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, 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: 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, code: 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,

10 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: 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: Namespaces: group variables, constants, and functions into logic Wolfgangsubsets. Eckhardt, Tobias Neckel: Object-oriented Programming in C++ Working with C and C++, June 30, 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: 14 // This is the implementation 15 # include " lennardjones.h" double lennardjones :: getforce ( const double & distance ) { 18 \ ldots 19 } code: Namespaces are predecessors of the identifier. Namespaces can be embedded into each other. Working with C and C++, June 30, int multiplybytwo ( int & x) { 18 x = x *2; 19 return x; 20 } 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 ; x = multiplybytwo (x); 30 std :: cout << "main (): x = " << x << std :: endl ; return 0; 33 } 4.2 Call-by-reference code: 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, 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, const References 4.3 Using C Libraries in C ++ 1 void foo ( i n t a, i n t b ) { } 4 5 void bar ( i n t & a, i n t & b ) { } 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 ) { } const references avoid side effects! (const) references belong to the signature overloading! Working with C and C++, June 30, 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, 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) ; 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, Working with C and C++, June 30,

11 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 ; 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, 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, Array Arguments 19 double computeaverage ( double grade [], int numberofgrades ) { 20 // } double computeaverage ( const double grade [], int numberofgrades ) { // } double computeaverage ( const double * grade, int numberofgrades ) { 28 // } double computeaverage ( const double * const grade, int numberofgrades ) { 32 // } double computeaverage ( double const * const grade, int numberofgrades ) { 36 // } code: This time, the user is not allowed to modify any entry of grade. Working with C and C++, June 30, int gradesbsc, gradesmsc [5]; 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 return 0; Pitfalls code: Working with C and C++, June 30,

12 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, Object Orientation in C++, July 1, What Is an Object? a car a cat a chair... a molecule a star a galaxy 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, Object Orientation in C++, July 1, 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, 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, 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, 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,

13 2 Objects in C 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, Object Orientation in C++, July 1, Bike.h - The class Keyword Bike.h - State: Member Variables 17 # ifndef BIKE_H_ 18 # define BIKE_H_ # include <cmath > 21 # include <iostream > # include " GearShift.h" 25 class Bike { 72 }; #endif // BIKE_H_ Keyword code: 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 ; //! current rpm 31 float m_revolutions ; //! gear shift 34 GearShift m_gearshift ; 72 }; State code: Member variables define the state of an object. Member variable can be built-in or custom objects. Object Orientation in C++, July 1, Object Orientation in C++, July 1, 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, 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, class Bike { 36 public : 37 /** 38 * Constructor 39 * Bike.h - Behaviour: Member Functions 40 i_numberofgears # gears 41 **/ 42 Bike ( int i_numberofgears ); /** 45 * Destructor 46 **/ 47 ~ Bike (); /** 50 * Changes the gear to the closest possible gear. 51 * 52 i_gear gear to change to. 53 **/ 54 void changegear ( int i_gear ); 72 }; code: Object Orientation in C++, July 1, class Bike { 36 public : Bike.h - Behaviour: Member Functions (2) 56 /** 57 * Brakes the bike. 58 **/ 59 void brake (); /** 62 * Accelerates the bike. 63 * 64 i_rpm revolutions per minute. 65 **/ 66 void changecadence ( float i_rpm ); 72 }; Behaviour code: Member functions: mutator methods: change internal state of an object (often setxxx()) Object Orientation in C++, July 1,

14 Bike.h - Behaviour: Member Functions (3) Bike.h - Access Control 25 class Bike { 36 public : /** 69 * Prints status of our bike. 70 **/ 71 void printinformation () const ; 72 }; Behaviour code: 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 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, Object Orientation in C++, July 1, 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, Object Orientation in C++, July 1, Bike.cpp - Constructor Bike.cpp - Member Initialisation List 17 # include " Bike.h" 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: 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: 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, Object Orientation in C++, July 1, Bike ::~ Bike () { 28 std :: cout << "bike destroyed :(" << std :: endl ; 29 } Properties Bike.cpp - Destructor code: 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 } void Bike :: brake () { 47 m_speed = std :: max ( 0.f, m_speed - 5.f ); 48 m_revolutions = m_speed * 25. f; 49 } 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, Object Orientation in C++, July 1,

15 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" int main () { 20 // construct two bikes 21 Bike l_mybike ( 20 ); 22 Bike * l_myfriendsbike = new Bike ( 15 ); 39 delete l_myfriendsbike ; 40 } code: 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, Object Orientation in C++, July 1, # include " Bike.h" 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 (); // 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 ); // print information 35 l_mybike. printinformation (); 36 l_myfriendsbike -> printinformation (); // 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, Object Orientation in C++, July 1, class SimpleClass { 20 // private : 21 static int s_simplecounter ; public : SimpleClass () { 25 s_simplecounter ++; Static Members 26 std :: cout << "ctr in constr =" << s_simplecounter << std :: endl ; 27 }; ~ SimpleClass () { 30 s_simplecounter - -; 31 std :: cout << "ctr in destr =" << s_simplecounter << std :: endl ; 32 }; 33 }; int SimpleClass :: s_simplecounter = 0; int main () { 38 SimpleClass l_simple1 ; 39 { 40 SimpleClass l_simple2 ; 41 } 42 SimpleClass l_simple3 ; 43 } Object Orientation in C++, July 1, class SimpleClass { 20 // private : 21 static int s_simplecounter ; public : SimpleClass () { 25 s_simplecounter ++; Static Members (2) 26 std :: cout << "ctr in constr =" << s_simplecounter << std :: endl ; 27 }; ~ SimpleClass () { 30 s_simplecounter - -; 31 std :: cout << "ctr in destr =" << s_simplecounter << std :: endl ; 32 }; 33 }; int SimpleClass :: s_simplecounter = 0; code: 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, 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 }; int SimpleClass :: s_simplecounter = 1; int main () { 31 SimpleClass :: printcounter (); 32 SimpleClass :: increasecounter (); 33 SimpleClass :: printcounter (); 34 } code: 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, class SimpleClass { 18 // private : 19 const int m_a ; public : 22 SimpleClass ( int i_a ): m_a ( i_a ) { 23 // forbidden assignment // m_a = 10; 25 }; 26 }; int main () { 29 SimpleClass l_simple ( 15 ); 30 } Const Members code: 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,

16 Const Member Functions 3 Inheritance 17 class SimpleClass { 18 // private : 19 int m_a ; public : 22 void simplefunctions () const { 23 // forbidden assignment // m_a = 5; 25 } 26 }; int main () { 29 SimpleClass l_simple ; 30 l_simple. simplefunctions (); 31 } code: 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, Object Orientation in C++, July 1, Inheritance in Real Life object Object Orientation in C++, July 1, 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, 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, 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, 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, Object Orientation in C++, July 1,

17 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, 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, 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 ; } virtual ~ Shape () {}; 27 }; class Star : public Shape {}; 30 class Circle : public Shape {}; 31 class Rectangle : public Shape {}; code: Shape is the base class for the derived classes Star, Circle and Rectangle 23 class Shape { // private : 25 int m_color ; public : 28 Shape ( int i_color =0 ): 29 m_color ( i_color ) {}; 30 virtual ~ Shape () {}; int getcolor () const { return m_color ; }; 39 }; code: code: Object Orientation in C++, July 1, Object Orientation in C++, July 1, Inheritance - Implementing a Child Class 41 class Circle : public Shape { 42 // private : 43 double m_radius ; 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: code: Accessibility Circle inherits from Shape note class definition Note: call of base class constructor in initialisation list Object Orientation in C++, July 1, class Circle : public Shape { 42 // private : 43 double m_radius ; 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: code: 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, 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 * 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, Object Orientation in C++, July 1,

18 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, 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, 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, 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, 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, Object Orientation in C++, July 1, 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, Object Orientation in C++, July 1,

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

20 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, Details of Object Orientation in C++, July 2, 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, Implementations and Interfaces (2) - Shape.h 17 class Shape { 18 // private : 19 int m_color ; public : 22 Shape ( int i_color =0 ); 23 virtual ~ Shape (); 25 int getcolor () const ; // purely virtual function 28 virtual double getsurfacearea () const = 0; // virtual function with default implementation 31 // virtual double getsurfacearea () const ; 32 }; Keyword code: 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, Implementations and Interfaces (3) - Circle.h Implementations and Interfaces (4) - Rectangle.h 18 class Circle : public Shape { 19 // private : 20 double m_radius ; public : 23 Circle ( double i_radius ); virtual ~ Circle (); virtual double getsurfacearea () const ; // 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: 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, Details of Object Orientation in C++, July 2, Implementations and Interfaces (5) - *.cpp 15 Shape :: Shape ( int i_color ): 16 m_color ( i_color ) { 17 } Shape ::~ Shape (){ 20 } int Shape :: getcolor () const { 23 return m_color ; } code: 17 Circle :: Circle ( double i_radius ): 18 Shape (), m_radius ( i_radius ) { 19 std :: cout << "constructed a circle, radius : " << m_radius << std :: endl ; 20 } 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 } Rectangle ::~ Rectangle () { 23 } 25 double Rectangle :: getsurfacearea () const { 26 return m_width * m_height ; 27 } code: code: Details of Object Orientation in C++, July 2, Details of Object Orientation in C++, July 2,

21 18 int main () { 19 Circle l_circle ( 2.3 ); 20 Rectangle l_rectangle ( 4.2, 1.8, 3 ); 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 } // not allowed for virtual function w/o default implementation 32 // Shape l_shape1 (); 33 return 0; 34 } code: 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, class Base { 20 // private : 21 public : 22 void staticprint () { 23 std :: cout << "base " << std :: endl ; } virtual void dynamicprint () { 27 std :: cout << "base " << std :: endl ; 28 } 29 }; 1.2 Static and Dynamic Decoding code: 31 class Derived : public Base { 32 // private : 33 public : 34 void staticprint () { 35 std :: cout << "derived " << std :: endl ; 36 } virtual void dynamicprint () { 39 std :: cout << "derived " << std :: endl ; 40 } 41 }; code: Details of Object Orientation in C++, July 2, Static and Dynamic Decoding (2) 1.3 Virtual Destructors 43 int main () { 44 Base l_base ; 45 l_base. staticprint (); 46 l_base. dynamicprint (); Derived l_derived ; 49 l_derived. staticprint (); 50 l_derived. dynamicprint (); Base * l_derivedpointer = & l_derived ; 53 l_derivedpointer -> staticprint (); 54 l_derivedpointer -> dynamicprint (); 55 } code: 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 }; class Derived : public Base { 29 // private : 30 public : 31 virtual ~ Derived () { std :: cout << "clean up after Derived " << std :: endl ; } 32 }; code: Details of Object Orientation in C++, July 2, Details of Object Orientation in C++, July 2, 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 ; Base * l_pointertobase = new Base ; 39 Derived * l_pointertoderived1 = new Derived ; 40 Base * l_pointertoderived2 = new Derived ; delete l_pointertobase ; 43 delete l_pointertoderived1 ; 44 delete l_pointertoderived2 ; // might cause trouble 45 return 0; 46 } code: Virtual destructors are bound to the type the object at creation. Details of Object Orientation in C++, July 2, 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 ; Base * l_pointertobase = new Base ; 39 Derived * l_pointertoderived1 = new Derived ; 40 Base * l_pointertoderived2 = new Derived ; delete l_pointertobase ; 43 delete l_pointertoderived1 ; 44 delete l_pointertoderived2 ; // might cause trouble 45 return 0; 46 } code: Non-virtual destructors are bound to the type of the pointer, which points to them. Details of Object Orientation in C++, July 2, 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, Details of Object Orientation in C++, July 2,

22 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 ; friend void modify ( Simple & io_simple ); 27 friend class Friend ; 28 friend class DerivedFriend ; 29 }; 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: friend allows functions or classes to access private and protected members Details of Object Orientation in C++, July 2, int main (){ 20 unsigned int l_uint1 = -1; 21 unsigned int l_uint2 = -2; 22 unsigned int l_uint3 = ; 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: What is the result of the operations above? You have five minutes.. Details of Object Orientation in C++, July 2, 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, 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, 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 ; return 0; 30 }; code: 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, 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, 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 ; Derived * l_pointertoderived4 = dynamic_cast <Derived * >( l_pointertoderived1 ); 39 Derived * l_pointertoderived5 = dynamic_cast <Derived * >( l_pointertobase ); 48 } Dynamic Cast code: 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, Dynamic Cast (2) 41 if( l_pointertoderived4 ) std :: cout << "first cast works " << std :: endl ; 42 else std :: cout << "first cast returns NULL " << std :: endl ; if( l_pointertoderived5 ) std :: cout << "second cast works " << std :: endl ; 45 else std :: cout << "second cast returns NULL " << std :: endl ; return 0; 48 } code: 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,

23 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 ); return 0; 36 } code: 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 ); 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 ; return 0; 41 } code: 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, Details of Object Orientation in C++, July 2, Const Cast Automatic / implicit conversions 19 void print ( int &i ) { 20 std :: cout << i << std :: endl ; 21 } int main () { const int l_int = 27; // not allowed : print (..) is allowed to modify l_int 27 // print ( l_int ); print ( const_cast <int & >( l_int ) ); return 0; 32 } code: 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 } int main () { 61 Circle l_circle ( 2.3 ); 62 printsurfacearea ( l_circle ); printsurfacearea (5.42) ; Int is implicitly converted to Shape. Can be avoided with keyword explicit! Details of Object Orientation in C++, July 2, Details of Object Orientation in C++, July 2, 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: 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, Details of Object Orientation in C++, July 2, 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: 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, Details of Object Orientation in C++, July 2,

24 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, 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: Details of Object Orientation in C++, July 2, 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 }; int main () { 31 SimpleClass l_simple1 ; 32 l_simple1. setvalues ( 1, " simple1 " ); 33 l_simple1. printvalues (); // call copy constructor 36 SimpleClass l_simple2 ( l_simple1 ); 37 l_simple2. printvalues (); 38 } code: 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: 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, Details of Object Orientation in C++, July 2, 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: 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, 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 }; int main () { 31 SimpleClass l_simple1, l_simple2 ; 32 l_simple1. setvalues ( 1, " simple1 " ); 33 l_simple1. printvalues (); // call the assignment operator 36 l_simple2 = l_simple1 ; 37 l_simple2. printvalues (); 38 } code: Details of Object Orientation in C++, July 2, 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: 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, 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: Again a manual implementation is possible and sometimes required; different signatures are possible Details of Object Orientation in C++, July 2,

25 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: 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: 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, 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, 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: Solution: Perform a deep copy in the copy constructor! Details of Object Orientation in C++, July 2, 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, 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 ; // 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 } return 0; 39 } Details of Object Orientation in C++, July 2, 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: Different predefined stream manipulators exist; precision & number format for example Details of Object Orientation in C++, July 2, 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 } return io_stream ; 44 } 45 }; 70 std :: cout << "tab insertion test : " << Tabber (3) << "done.." << std :: endl ; code: Operator overloading of << and >> allows for custom implementations Details of Object Orientation in C++, July 2, 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 } for ( int i = 0; i < 100; i ++) { 15 out << i << " " << std :: endl ; 16 } Details of Object Orientation in C++, July 2,

26 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 } 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, Details of Object Orientation in C++, July 2, 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, Details of Object Orientation in C++, July 2,

27 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, Templates & Standard Template Library (STL), July 3, 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 ; int numdvds ; 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 ; int numactors ; 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 ; int numdvds ; DVD * dvds [5]; 5 # include <string > 6 7 class DVD ; 8 9 class Actor { private : 12 std :: string name ; int numdvds ; Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3, 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, Templates & Standard Template Library (STL), July 3, 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, #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,

28 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, Templates & Standard Template Library (STL), July 3, 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, 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 } 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: Naive Approach Copy & paste Code duplication Templates & Standard Template Library (STL), July 3, 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 ; return l_result ; 30 } 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 ; Custom l_custom1 (1), l_custom2 (2) ; 39 // add ( l_custom1, l_custom2 ); not allowed return 0; 42 }; code: Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3, 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 ; return l_result ; 30 } int main (){ 38 Custom l_custom1 (1), l_custom2 (2) ; 39 // add ( l_custom1, l_custom2 ); not allowed return 0; 42 }; code: Templates & Standard Template Library (STL), July 3, 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]; for ( int l_entry = 1; l_entry < i_size ; l_entry ++ ) { 23 l_result *= i_values [ l_entry ]; } return l_result ; 27 } int main (){ 30 double l_array [5] = { -1.5, 1.4, 5.2, -6.1, 2.9}; std :: cout << product (l_array, 5) << std :: endl ; 33 std :: cout << product (l_array, 5.2) << std :: endl ; // implicit cast to int return 0; 36 }; code: Templates & Standard Template Library (STL), July 3,

29 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 } } 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 return 0; 33 }; Templates & Standard Template Library (STL), July 3, Assume that we want to implement a generic class: 22 class PairDouble { 23 // private : double m_firstvalue ; 25 double m_secondvalue ; public : 28 PairDouble ( double i_first, double i_second ): 29 m_firstvalue ( i_first ), 30 m_secondvalue ( i_second ) {}; 31 }; class PairInt { 34 // private : 35 int m_firstvalue ; 36 int m_secondvalue ; 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, 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 ; public : 53 Pair ( T i_first, T i_second ): 54 m_firstvalue ( i_first ), 55 m_secondvalue ( i_second ) {}; 56 }; code: Templates & Standard Template Library (STL), July 3, 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: Templates & Standard Template Library (STL), July 3, 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 ; // not allowed : template parameter missing 67 // Pair ( 1, 2 ); // not allowed : different template classes 70 // l_pairlong = l_pairint1 ; 71 // Pair <long > l_pairlong2 ( l_pairint1 ); return 0; 74 }; code: 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 ; T1 m_firstarray [ SIZE ]; T2 m_secondarray [ SIZE ]; SoA (): m_size ( SIZE ) {}; 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: Class template parameter list can contain one or more of: type non-type (but value) templates (upcoming) Templates & Standard Template Library (STL), July 3, 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 ; 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 } l_soa. print (); 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: Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3,

30 4 Standard Template Library (STL) Survey of STL - html:// 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 ( as test field for extensions Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3, 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 } for ( int i =0; i < 5; i ++) { 13 std :: cout << numbers [i] << std :: endl ; 14 } 15 return 0; 16 } code: 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, Templates & Standard Template Library (STL), July 3, 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: 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 } for (list <int >:: iterator it = numbers.begin (); 15 it!= numbers. end (); it ++) { 16 std :: cout << *it << std :: endl ; 17 } code: Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3, 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! Templates & Standard Template Library (STL), July 3, Templates & Standard Template Library (STL), July 3,

Object-oriented Programming in C++

Object-oriented Programming in C++ Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel March 23, 2015 Working with C and C++, March 23, 2015 1 Challenges of This Course Heterogeneity of the audience

More information

Object-oriented Programming in C++

Object-oriented Programming in C++ 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

More information

Object-oriented Programming in C++

Object-oriented Programming in C++ Object-oriented Programming in C++ Object Orientation in C++ Wolfgang Eckhardt, Tobias Neckel July 1, 2014 Object Orientation in C++, July 1, 2014 1 1 The Concept of Object Orientation Object Orientation

More information

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

6. Pointers, Structs, and Arrays. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

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

6. Pointers, Structs, and Arrays. March 14 & 15, 2011 March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

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

Part V. Object-oriented Programming. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part V Object-oriented Programming Compact Course @ Max-Planck, February 16-26, 2015 65 What Is an Object? Compact Course @ Max-Planck, February 16-26, 2015 66 What Is an Object? a car a cat a chair...

More information

4. Functions. March 10, 2010

4. Functions. March 10, 2010 March 10, 2010 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 40 Outline Recapitulation Functions Part 1 What is a Procedure? Call-by-value and Call-by-reference Functions

More information

5. Applicative Programming. 1. Juli 2011

5. Applicative Programming. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 41 Outline Recapitulation Computer architecture extended: Registers and caches Header files Global variables

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

10. Object-oriented Programming. 7. Juli 2011

10. Object-oriented Programming. 7. Juli 2011 7. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Object Case Study Brain Teaser Copy Constructor & Operators Object-oriented Programming, i.e.

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

8. Object-oriented Programming. June 15, 2010

8. Object-oriented Programming. June 15, 2010 June 15, 2010 Introduction to C/C++, Tobias Weinzierl page 1 of 41 Outline Recapitulation Copy Constructor & Operators Object-oriented Programming Dynamic and Static Polymorphism The Keyword Static The

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

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

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

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.

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. 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. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

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

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

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

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

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

Lecture 10: building large projects, beginning C++, C++ and structs CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 10:

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

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

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

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:

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: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

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

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Lecture 14: more class, C++ streams

Lecture 14: more class, C++ streams CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

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

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Lecture 13: more class, C++ memory management

Lecture 13: more class, C++ memory management CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 13:

More information

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

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

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

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

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

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

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

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

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:

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: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

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

Reliable C++ development - session 1: From C to C++ (and some C++ features) Reliable C++ development - session 1: From C to C++ (and some C++ features) Thibault CHOLEZ - thibault.cholez@loria.fr TELECOM Nancy - Université de Lorraine LORIA - INRIA Nancy Grand-Est From Nicolas

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

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

For Teacher's Use Only Q No Total Q No Q No Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9

More information

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

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

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

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

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

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

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

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

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

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Engineering Tools III: OOP in C++

Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Why C++? C++ as a powerful and ubiquitous tool for programming of numerical simulations super-computers (and other number-crunchers)

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:

More information

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Software Engineering /48

Software Engineering /48 Software Engineering 1 /48 Topics 1. The Compilation Process and You 2. Polymorphism and Composition 3. Small Functions 4. Comments 2 /48 The Compilation Process and You 3 / 48 1. Intro - How do you turn

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

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

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

PHY4321 Summary Notes

PHY4321 Summary Notes PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t

More information

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

G52CPP C++ Programming Lecture 7. Dr Jason Atkin G52CPP C++ Programming Lecture 7 Dr Jason Atkin 1 This lecture classes (and C++ structs) Member functions inline functions 2 Last lecture: predict the sizes 3 #pragma pack(1) #include struct A

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

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

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

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

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

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

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2 Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information