Object-oriented Programming in C++

Size: px
Start display at page:

Download "Object-oriented Programming in C++"

Transcription

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

2 Challenges of This Course Heterogeneity of the audience (different level of programming experience, different programming languages, etc.); We assume: Experience in procedural programming (FORTRAN, C, or similar) availability of a notebook with some C++ compiler (Details on installation for win in Tutorial 1) Variety of topics related to C++ selection of topics! General: Giving a lecture on how to swim won t work participants have to jump into water (i.e. program!) Restricted amount of time long-term learning effects not without using C++ for different tasks yourself! Working with C and C++, June 30,

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

4 Outline of Day 1 Basic usage From text files to binary code header files vs. implementation files C ++ as an increment of C Basics of C memory management: data types, pointers, control structures (loops/if/switch) functions call by value vs. reference... From C to C ++ (Extensions) namespaces references... Working with C and C++, June 30,

5 Outline of Day 2 & 3 Object-oriented Programming Concepts/way of thinking Syntax in C++ Inheritance (taxonomy) Information hiding OO Continued Polymorphism Overloading, deep vs. shallow copy Type conversion, explicit (temporary objects) Usage of const File I/O Working with C and C++, June 30,

6 Outline of Day 4 Templates & the Standard Template Library STL Understanding templates (templated function, templated class) The Standard Template Library Using templates and STL for data structures (containers) and algorithms Working with C and C++, June 30,

7 What Will NOT be Covered in This Course and is nevertheless interesting/relevant: exception handling assertions details on libraries (static vs. shared) details on design patterns preprocessor commands and macros makefiles & Co. automatic testing (cppunit etc.) automatic code documentation (doxygen, doxys, etc.) debugging with gdb, valgrind & Co. Working with C and C++, June 30,

8 Organisation of This Course Persons: Day 1+2: Tobias Neckel Day 3+4: Wolfgang Eckhardt Times: 4 days: 2h lecture + 2h tutorials each Website: General infos: 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,

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

10 1 Basic Usage Working with C and C++, June 30,

11 1.1 From Text Files to Binary Code as in FORTRAN, source code needs to be compiled: source: Working with C and C++, June 30,

12 Comments in C / C ++ 1 // one line comment 3 /* 4 several lines 5 */ 7 /** 8 * several lines, autodocutool syntax : 9 * 10 * This file is part of the C++ course. 11 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,

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

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

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

16 A Second Example: More Than One File 13 # include <iostream > 14 # include " computations.h" int main () { 17 std :: cout << " adding via function : 5+11= " << add_values (5,11) << std :: endl ; 18 return 0; 19 } code: 1 /** 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,

17 Compilation of Two Files Variant 1: compile & link simultaneously 1 g++ -O3 -g second_example. cpp computations. cpp -o second_v1 Variant 2: Step 1: compile Step 2: link passing the object files to the linker, or passing the library files (a,so) due to the -l argument with -L giving the compiler the library search path. 1 g++ -O3 -g -c second_example. cpp computations. cpp 2 g++ -O3 -g second_example.o computations.o -lm -o second_v2 Working with C and C++, June 30,

18 Naming Conventions for Files type C C ++ implementation.c.cpp.cxx.c.cc header.h.h.hpp.hxx Working with C and C++, June 30,

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

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

21 2 C ++ as an increment of C Working with C and C++, June 30,

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

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

24 3 Basics of C Working with C and C++, June 30,

25 Syntax vs. Semantics Syntax = rules for the constructing of sentences in the languages The syntax is (more or less) prescribed by C. Semantics = meaning of sentences, words, or fragments. The semantics is what you had in mind, i.e. the reader has to reconstruct it from your program. Best practices: Use meaningful names! Add documentation, documentation, and documentation! If code is not documented, it does not exist! Working with C and C++, June 30,

26 3.1 Built-in Data Types int integer value (signed) short int integer (typ. 16 bytes) long int integer (typ. 32 bytes) unsigned int int (purely positive) double floating point number (double prec.) float floating point number (single prec.) char character bool boolean type (only C ++) Working with C and C++, June 30,

27 Built-in Data Types - int 20 int i; 21 int k; 22 i = 5; 23 k = -1; 24 std :: cout << "i+k=" << i+k << std :: endl ; 25 unsigned int l = 25; 26 std :: cout << "k+l=" << k+l << std :: endl ; Here, some C / C ++ syntax obvious: Declaration/definition of variables Assignment of variable values note: = different to == note: garbage value of variable if no assignment! Working with C and C++, June 30,

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

29 Built-in Data Types - float 40 float d = 3 e38 ; 41 std :: cout << "d=" << d << std :: endl ; 42 d = 3 e39 ; 43 std :: cout << "d=" << d << std :: endl ; 44 float pi = ; 45 std :: cout << " pi=" << pi << std :: endl ; Note: default number of printed digits: 6 (change possible, see streams below) Working with C and C++, June 30,

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

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

32 Built-in Data Types & Memory Memory int x; char y; float z; 21: y // one byte 22; z // four bytes 23; 24; 25; 26; x // two bytes? 27; 28: A variable corresponds to memory location and holds a value. Compiler cares for memory layout. Working with C and C++, June 30,

33 Constants 1 i n t ConstantA = 1; 2 double ConstantB = 0. 4 ; 3 double ConstantC = ; 4 5 void main ( ) { } Constants are treated similar to source code, i.e. translated by the compiler into bit sequences. Some very simple constants can be embedded into the micro codes (assembler). At startup, all others are loaded into the memory. Working with C and C++, June 30,

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

35 Memory Organisation for Variables Whole memory per application: split up into segments (or sections). Linker can determine their size. Search for free memory: only done for heap data. Other variables: created (and destroyed) one by one on the stack segment. Exception: Variables not declared within main or any other function, but outside. Those are global/static variables held by a different segment. Each object file holds a specification for the segments (sizes). The linker then merges them into one big memory layout. Working with C and C++, June 30,

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

37 Type Inference - Example 1 15 # include <iostream > int main () { // Example 1 20 unsigned int u = 2; 21 int i = 1; 22 double d; 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 ; code: Working with C and C++, June 30,

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

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

40 3.4 Recap: Scopes, Loops & Branches The concept of the scope: A variable has to be declared within the same brackets { }. Otherwise, compiler searches within the enclosing brackets (not within the neighbours). The brackets define a scope. The outer brackets define an outer scope. Some compilers allow the programmer to redefine variables within subscopes. This hides variables they are not overwritten. Working with C and C++, June 30,

41 Recap: Loops Loops render the programming style applicative programming. Types of loops: while, do-while, for. Concept: should be known. Syntax: 1 while ( expression ) { 2 / / something i n t e l l i g e n t 3 } 4 5 do { 6 / / something i n t e l l i g e n t 7 } while ( expression ) ; Working with C and C++, June 30,

42 Recap: The For Loop 1 f o r ( i n t a=0; a<20; a++) { 2 / / something i n t e l l i g e n t 3 } for statements: opens a new scope Statement int a: creates a new variable (loop counter) within this scope Statement a<20: termination criterion (evaluated before the upcoming iteration) Statement a++: increment of the loop counter Working with C and C++, June 30,

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

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

45 Recap: Branches (2) 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 } code: Attention: do not forget the break statement! Working with C and C++, June 30,

46 3.5 Functions Syntax of function definitions: 1 r e t u r n t y p e functionname ( paramtype paramname ) { 2 / / do something i n t e l l i g e n t 3 } Functions define a scope due to the brackets { } (basis block). Variables of other scopes are not defined within the function. Working with C and C++, June 30,

47 Functions - Examples 17 void nothing ( void ); // function prototype 18 void nothing2 (); // function prototype 19 void timesx ( int x); // function prototype 20 int area (int, int ); // function prototype 21 int area2 ( int a, int b); // function prototype void nothing ( void ) { 24 std :: cout << " do nothing :-)" << std :: endl ; 25 } 26 void nothing2 () { 27 std :: cout << " do nothing again " << std :: endl ; 28 } 29 void timesx ( int x) { 30 for ( int i =1; i <=x; i ++) { 31 std :: cout << "*" << std :: endl ; 32 } 33 } 34 int area ( int a, int b) { 35 return a*b; 36 } 37 int area2 ( int a, int b) { 38 return a*b; 39 } code: Working with C and C++, June 30,

48 17 double foo ( double a, double h) { 18 if (h ==0) { 19 return 0.0; 20 } 21 if (a ==0) 22 return ; // error 23 // do something complicated with a and h 24 return a /10.0; 25 } 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,

49 17 int sign ( int a) { 18 // return sign 19 } double change_sign ( double b) { 22 // change sign and return new value 23 } 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,

50 17 int sign ( int a) { 18 // return sign 19 } double change_sign ( double b) { 22 // change sign and return new value 23 } 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,

51 3.6 Call-by-value vs. Call-by-Reference Questions to be tackled: What happens with parameters in functions when being called? Can functions modify outside variables? What do you know already? Working with C and C++, June 30,

52 15 # 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,

53 Call-by-value In C/C++, parameters (arguments) are passed call-by-value. Functions work on copies of the original variables. The original variables are saved away on the call stack. As soon as the operation terminates, the old variable values are restored. Working with C and C++, June 30,

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

55 const Modifier We can mark any argument to be a const argument, i.e. the function is not allowed to modify it. 1 void foo ( const i n t a ) { } const allows compiler to optimise code aggressively. const allows you to write bug-safe code (user cannot modify a variable by accident). const closes (some of) the performance gap between C / C ++ and FORTRAN. Working with C and C++, June 30,

56 3.7 Signature of a Function 1 i n t foo ( ) 2 i n t bar ( ) 3 i n t foo ( i n t a ) 4 i n t foo ( double x ) 5 i n t foo ( i n t a, const double b, double x ) A function is unique due to its name, and due to the number of arguments, and due to the type of the arguments, and due to the const modifiers of its arguments Everything besides the name: signature. name + signature function unique. Attention: return value does not come into play! Working with C and C++, June 30,

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

58 3.8 Pointers Memory 21: 22; 20 // int a 23; 24; 25; 26; 27; 28: The memory is enumerated using an integer. Pointers are variables that hold the memory number (address) instead of a value. 1 / / holds an i n t ; 2 i n t a ; 3 / / holds address o f an i n t 4 i n t * p ; Working with C and C++, June 30,

59 Pointers and Addresses 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; code: Working with C and C++, June 30,

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

61 When to Use Pointers 1 void foo ( i n t * a ) { 2 ( * a ) ++; a++; / / That could not have happened w i t h references 5 } Pointers are difficult to handle (lots of syntactic overhead). We know how to do it, but do collaborators know? Avoid it whenever possible. Use C++ references instead. Working with C and C++, June 30,

62 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. 24 */ 25 double dotproduct ( 26 const double & x1, 27 const double & x2, 28 const double & y1, 29 const double & y2 30 ) { 31 return x1* y1 + x2* y2; 32 } 3.9 Arrays code: 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,

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

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

65 Arrays & Pointers 1 double grade [ 4 ] ; 2 grade [ 0 ] = 1. 3 ; 3 grade [ 2 ] = 3. 3 ; 4 grade [ 3 ] = 1. 0 ; 5 grade [ 1 ] = 4. 0 ; 6 7 double * p = grade ; 8 i f ( grade [ 0 ] = = * p )... / / always t r u e 9 i f ( grade [ 1 ] = = * ( p+1) )... / / always t r u e Name of array == pointer to the first element of array Array element access: internally implies pointer arithmetics and dereferencing Attention pointers: range checks (size of array) not automatically! Working with C and C++, June 30,

66 Dot Product Revisited We need a range variable 1 double dotproduct ( 2 double * x, 3 double * y, 4 i n t n 5 ) { 6 double r e s u l t = 0. 0 ; 7 f o r ( i n t i =0; i <n ; i ++) { 8 r e s u l t += * ( x+ i ) + * ( y+ i ) ; 9 } 10 r e t u r n r e s u l t ; 11 } Working with C and C++, June 30,

67 Dynamic Arrays ( C ++ Style) 1 double * grades = new double [ 4 5 ] ; 2 3 d e l e t e [ ] grades ; We can create arrays on the heap. Size might be a variable, too. Corresponding delete has to be a delete[]. delete without brackets just deletes the first value. There is a performance reason for two different delete operators. If we omit delete, we will get a memory leak. If we use the array after delete or before new, it points to garbage (remember: grades is only a pointer). Working with C and C++, June 30,

68 19 double matrix [4][4]; 20 Multidimensional Arrays 21 for ( int i=0; i <4; i++) { 22 for ( int j=0; j <4; j++) { 23 // conditional assignment 24 matrix [i][ j] = i==j? 1.0 : 0.0; 25 std :: cout << "m[" <<i<<"][" <<j<<"]=" << matrix [i][ j] << std :: endl ; 26 } 27 } 28 matrix [2][1] = 5.0; 29 // matrix [12] = 12.0; // does not compile! 30 * matrix [1] = 12.0; 31 * matrix [17] = 12.0; // compiles, but...!? try compile with -O0 code: 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,

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

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

71 4 From C to C ++ (Extensions) Working with C and C++, June 30,

72 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_ code: Sometimes, functions and variables have the same name as they were developed by different authors and written into different files. It is very difficult to distinguish between these names, i.e. we Working with C and C++, June 30,

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

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

75 17 int multiplybytwo ( int & x) { 18 x = x *2; 19 return x; 20 } int main () { 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,

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

77 const References 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,

78 4.3 Using C Libraries in C ++ C 99 C++ 98 C ++: Large standard library in comparison to C In principle, all C headers in C ++ usable Naming conventions of headers: 1 # i n c l u d e <math. h> => # i n c l u d e <cmath> 2 # i n c l u d e <s t d l i b. h> => # i n c l u d e <c s t d l i b > Much more in the upcoming days. Working with C and C++, June 30,

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

80 Default Arguments of Functions 1 void foo ( i n t a=3) ; 2 void bar ( ) ; 3 void bar ( i n t b=3) ; / / not allowed 4 void tee1 ( i n t c, double d =2.0) ; 5 void tee2 ( i n t c =2, double d ) ; / / not allowed 6 void tee3 ( i n t c =2, double d =4.0) ; 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,

81 Pointer Syntax The pointer operator binds to the right neighbour. 1 i n t a ; 2 i n t * b1 ; 3 i n t * b2 ; 4 i n t * b3 ; 5 i n t * c1, c2 ; 6 i n t * c3, * c4 ; 7 i n t * c5, c6 ; 8 i n t * c7, * c8 ; 9 i n t * * c9 ; 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,

82 Pointers and Scopes 1 i n t * p ; 2 f o r ( i n t i =0; i <2; i ++) { 3 i n t a = 2 * i ; 4 p = &a ; 5 6 std : : cout << a << std : : endl ; 7 std : : cout << * p << std : : endl 8 } 9 std : : cout << a << std : : endl ; / / does t h i s work? 10 std : : cout << * p << std : : endl ; / / does t h i s work? With pointers, we can violate the end-of-scope rules, i.e. we can access variables that do not exist anymore. This is the principle of all these buffer overrun malware codes. Working with C and C++, June 30,

83 Array Arguments 19 double computeaverage ( double grade [], int numberofgrades ) { 20 // } double computeaverage ( const double grade [], int numberofgrades ) { 24 // } 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,

84 Pitfalls 19 int gradesbsc, gradesmsc [5]; gradesmsc [5] = 2.3; 22 gradesmsc [3]++; 23 int * p0 = gradesmsc ; 24 int * p1 = & gradesmsc [0]; 25 int * p2 = & gradesmsc [1]; 26 gradesmsc ++; // does not work 27 p2 ++; // arrrgh return 0; code: Working with C and C++, June 30,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

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

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

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

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

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

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

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

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

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

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

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

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

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

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

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

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

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

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

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

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

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 1. Pointers As Kernighan and Ritchie state, a pointer is a variable that contains the address of a variable. They have been

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

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

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

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

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

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

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

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

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

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

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

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

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

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

C++ Programming for Non-C Programmers. Supplement

C++ Programming for Non-C Programmers. Supplement C++ Programming for Non-C Programmers Supplement ii C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by itcourseware, 10333 E. Dry Creek Rd., Suite 150, Englewood,

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

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

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

C++ Programming Lecture 1 Software Engineering Group

C++ Programming Lecture 1 Software Engineering Group C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

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

Looping and Counting. Lecture 3 Hartmut Kaiser  hkaiser/fall_2012/csc1254.html Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html Abstract First we ll discuss types and type safety. Then we will modify the program

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

C++ Support Classes (Data and Variables)

C++ Support Classes (Data and Variables) C++ Support Classes (Data and Variables) School of Mathematics 2018 Today s lecture Topics: Computers and Programs; Syntax and Structure of a Program; Data and Variables; Aims: Understand the idea of programming

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

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

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

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

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

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

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

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

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

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

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

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

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

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

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

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments

More information

Computer Science II Lecture 2 Strings, Vectors and Recursion

Computer Science II Lecture 2 Strings, Vectors and Recursion 1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed

More information

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

More information

C++ For Science and Engineering Lecture 12

C++ For Science and Engineering Lecture 12 C++ For Science and Engineering Lecture 12 John Chrispell Tulane University Monday September 20, 2010 Comparing C-Style strings Note the following listing dosn t do what you probably think it does (assuming

More information

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

C++ basics Getting started with, and Data Types. C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding

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

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

Looping and Counting. Lecture 3. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract First we ll discuss types and type safety. Then we will modify the program we developed last time (Framing

More information