IBM Research – Zurich Process Management Technologies Fortgeschrittene Programmierung in C++ Vorbesprechung & 1. Vorlesung Thomas Gschwind <thg at zurich ibm com> © 2013 IBM Corporation IBM Research – Zurich Process Management Technologies Overview Administrative Issues – Prerequisites & Goals – Schedule – Exams & Grading C++ – – – – 2 Introduction (“Hello World”) Functions and Operators Object-Based Programming (Classes and Structures) Namespaces Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Prerequisites Programming Languages – Java, maybe better C – Basic knowledge of object-oriented programming For students in the third semester or later 3 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Goals Learn to use different programming paradigms – Procedural programming – Object-based programming (templates, static polymorphism) – Object-oriented programming (inheritance, dynamic polymorphism) Hot Topics – Typing • Strong vs. weak typing • Static vs. dynamic typing – Templates – Exception Handling – Standard Library Arduino UNO SDK uses C++ Provides 32k Flash 4 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Grading Exercises will be handed out after each lecture – – – – Exercises SHOULD be solved in groups of two Exercises will be evaluated during two oral evaluation sessions Oral Lab Submission 1: Exercises from lectures 1 to 5 Oral Lab Submission 2: Exercises from lectures 6 to 10 Written exam at the end of the course – – – – – No material is allowed during the exam Exam supervisor can be used as API reference during the exam Yes, you will be asked to write code on paper Approx. 50-70% theory, 30-50% practical questions Exam MAY be oral if less than 10 students attending Grading – Exercises determine 1/3 of the final grade – Exam determines 2/3 of the final grade 5 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Organization & Schedule Announcements via the course web page – http://researcher.watson.ibm.com/researcher/view_project.php?id=5013 – Urgent announcements by email (mailing list seal-cpp) Approx. 12 lectures, 1.5 hours each – Thu. 8:10-9:45 BIN 2.A.10. – Tentatively, no lectures will be taught on Oct 23 and Dec 11 (however may change depending on my IBM activities) – For a complete schedule, please check the web Exercise submissions and Exam – Exercises due: • Thu. Oct 30, 8:00 BIN 2.A.10, • TBD: Thu. Dec. 18, 8:00 BIN 2.A.10 OR Thu. Jan. 8, 10:00. – Exam on: • Thu. Jan. 8, 8:10 BIN 2.A.10. 6 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Q & A? Course material? – Slides Books? – Bjarne Stroustrup. The C++ Programming Language (4th. ed.). Addison-Wesley. – Stanley B. Lippman, Josée Lajoie, Barbara E. Moo. C++ Primer. Addison-Wesley. – Check out your local book store Which operating system/C++ compiler? – Unix/Windows/OSX – GNU C++ (strongly recommended) 7 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies A Request from Your Lecturer If anything is unclear – Please ask questions – This makes the lecture more lively and interesting If you find mistakes in the slides – Please point them out, if you are unsure, privately after the lecture – Improves the quality of the lecture When I compare C++ with other programming languages – – – – 8 Of course, I will stress the advantages of C++ Yes, C++ has its downsides, we will address them as well After all, a programming languages are tools You SHOULD be able to use any of them to develop readable programs Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Overview Administration Issues – Prerequisites & Goals – Schedule – Exams & Grading C++ – – – – 9 Introduction (“Hello World”) Functions and Operators Object-Based Programming (Classes and Structures) Namespaces Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Introduction Historically speaking, – C++ is an Algol like programming language (like Pascal, or Java without OO features) – C++ builds on the C language of which it is a superset (except for comments, struct, enum, …) C++ adds several features to C such as – Inheritance – Templates – Exceptions C++ supports different programming paradigms – Procedural programming – Object-based programming – Object-oriented programming 10 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies “Hello World” This is the C++ way of saying “import”. hello.cc #include <iostream> using namespace std; No “class” statement necessary. int main(int argc, char *argv[]) { cout << "Hello World!" << endl; return 0; } C++’s fancy way of saying “System.out”. 11 This stands for print. Th. Gschwind. Fortgeschrittene Programmierung in C++. Move to the next line. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies “Hello World”: Compilation C++ is typically compiled to native code Every file is compiled to an object file Finally, files are linked This compiles our source file and generates an object *shell* tom@navelli:~/ak3-01$ g++ -c hello.cc file. tom@navelli:~/ak3-01$ g++ -o hello hello.o tom@navelli:~/ak3-01$ ./hello Hello World! tom@navelli:~/ak3-01$ This executes our program. 12 Th. Gschwind. Fortgeschrittene Programmierung in C++. This links the object file. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions May occur outside of classes – This is useful for routines that do not naturally belong to a specific class Support a variety of parameter passing options Supports overloading – Different functions may have the same name – The argument types are used to resolve the function to be executed – The return type is not considered for overloading resolution (This would overly complicate the function resolution algorithm) Functions can be used to define new operators Functions may be inlined – This may be requested using the inline keyword – Instead of invoking the function, the functions code will be replicated whenever the function should be invoked 13 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions: Parameter Passing Call by Value – Argument to be passed copied from the caller’s scope into the callee’s scope – Callee operates on its own copy Call by Reference/Pointer – Callee receives a references to the argument passed by the caller – Callee operates on caller’s copy C++/C – All parameters can be passed by value, by pointer, or in C++ also by reference Java – Primitive types are passed by value – Class instances are passed by reference C# – Value types (primitives and structs) by value or reference – Class instances by reference 14 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions: References Point to the address of the argument in the caller’s scope Argument in caller’s scope must be an lvalue Similar to – VAR parameter in Pascal – ref parameter in C# – Using pointers in C c++-swap.cc void swap(int &a, int &b) { int c=a; a=b; b=c; } 15 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions: Pointers Pointer’s are similar to references Caller has to pass a pointer to an object in his scope using the & operator => more explicit Pointers are traditionally used in C c-swap.c void c_swap(int *a, int *b) { int c=*a; *a=*b; *b=c; // printf("&a=%p, a=%p, *a=%d\n", &a, a, *a); // printf("&b=%p, b=%p, *b=%d\n", &b, b, *b); } 16 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions: inline Replaces the function call with the function’s body – Code needs to be known during compile time When to use it? – Useful for small functions – Sometimes also for larger ones Faster and more compact code For C Developers – – – – 17 Combines advantages of macros and functions Own area for parameters and variables No side effects As efficient as macros (if possible) Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Functions: A Comprehensive Example #include <cstdlib> #include <iostream> using namespace std; functions.cc inline void swap(int &a, int &b) { int c=a; a=b; b=c; } int gcf(int a, int b) { if (a<b) swap(a, b); while (b!=0) { a=a-b; if (a<b) swap(a, b); } return a; } inline int lcm(int a, int b) { return (a/gcf(a,b))*b; } void main(int argc, char *argv[]) { cout << gcf(atoi(argv[1]), atoi(argv[2])) << endl; cout << lcm(atoi(argv[1]), atoi(argv[2])) << endl; } 18 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Operators C++ supports user-defined operators Operators are mapped onto a binary function with the name operator prepended to the operator struct fraction { // type def int cntr; int denom; }; fraction operator*(fraction a, fraction b) { fraction c; c.cntr=a.cntr*b.cntr; c.denom=a.denom*b.denom; return c; } fraction foo(fraction a, fraction b, fraction c) { return a+b*c; } 19 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Operators: Input & Output Two operators are used for input and output – Input – Output operator>> operator<< cout cout << << “Hello “Hello World!” World!” << << endl; endl; (cout << “Hello World!”) << endl; operator<<(cout, “Hello World!”); operator<<(cout, endl); operator<<( operator<<(cout, “Hello World!”), endl); 20 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Operators: Guidelines Some people consider operator overloading – Because one could overload them in meaningless ways In this respect adhere to their established mathematical properties – – – – foo==foo foo==bar ⇔ bar==foo foo==bar ∧ bar==foobar ⇒ foo==foobar foo!=bar ⇔ !(foo==bar) Reflexivity Symetry Transitivity Consider mathematical laws – foo+=bar ⇔ foo=foo+bar – Associativity, Commutivity, … 21 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Operators User-definable operators – +, -, *, /, %, ^, &, |, ~, !, =, <, >, +=, -=, *=, /=, %=, ^=, &=, |=, <<, >>, >>=, <<=, ==, !=, <=, >=, &&, ||, ++, --, ->*, ,, ->, [], (), new, new[], delete, delete[] Not user-definable – ::, ., .* 22 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Object-Based Programming (Classes and Structures) Encapsulation – Add structure to the program – Explicit interface (Access to class checked by compiler) – User only needs to know this interface – Hide implementation details Useful for abstract data types such as stack, vector, map, … User-defined types – Allows developers to develop types that behave like primitive types – One of the key differences between C++ and C (or Java) 23 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Declaration and Definition (C++ and Java) // “same” as class fraction { // type def { cntr=c; denom=d; } private: int cntr; int denom; class Fraction { // type def private int cntr; private int denom; public: fraction(int c=0, int d=1) : cntr(c), denom(d) {} }; 24 public Fraction(int c, int d) { cntr=c; denom=d; } int get_counter() { return cntr; } public int getCounter() { return cntr; } void set_counter(int cntr) { this->cntr=cntr; } public void setCounter(int cntr) { this.cntr=cntr; } fraction operator*(fraction b) { … return result; } public Fraction mul(Fraction b) { … return denom; } … … }; Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Using them In Java void main(String[] args) { Fraction f=new Fraction(Integer.parseInt(args[1]), Integer.parseInt(args[2])); System.out.println(f.getCounter()+":"+ f.getDenominator()); } In C++ void main(int argc, char *argv[]) { fraction f(atoi(argv[1]), atoi(argv[2])); cout << f.get_counter() << ":" << f.get_denominator() << endl; } 25 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Access Control (Encapsulation) public: – Members declared in this section maybe used everywhere (default for structures) private: – Things declared here may only be used by this class – Useful for helper methods and attributes (default for classes) protected: – Things declared here may only be used by this class and its subclasses friend – Something different but somewhat similar to package in Java 26 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Construction & Destruction Constructor (T) – Executed after memory allocated for an object Destructor (~T) – Executed before memory will be deallocated for an object – Similar but better than Java‘s finalize() method (well defined when it will be executed) – Allows you to free additional resources class Fraction { public: Fraction(...) { // … } ~Fraction() { // … } }; 27 // Constructor // Destructor Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Constructors Default Constructor (T()) – Created by the compiler, if not defined by yourself – Initializes attributes with default constructor Copy Constructor (T(const T&)) – Created by the compiler, if not defined by yourself – Copies each attribute from the source to the target object („shallow copy“) – This constructor is executed frequently • Whenever a parameter is passed by value • Whenever an value is returned from a function (not if a pointer or reference to the value is returned) 28 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Default Artifacts Each class gets the following artifacts for “free” (that is, if they are not declared, C++ will provide them) – – – – 29 Default constructor Copy constructor Destructor Assignment operator Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Constructors class fraction { // type declaration+definition int c; int d; public: fraction(int cntr=0, int denom=1) : c(cntr), d(denom) {} // possibly redundant fraction(const fraction &f) : c(f.c), d(f.d) {} ~fraction() {} fraction &operator=(fraction b) { c=b.c; d=b.d; } fraction operator+(fraction b); fraction operator-(fraction b); }; Yes, that’s the same as the compiler-generated one, but many people consider it as good practice to define it yourself anyways 30 Th. Gschwind. Fortgeschrittene Programmierung in C++. What’s this? This initializes the members of this class in a more efficient way (for built-in types it’s actually the same) © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Disable Default Artifacts If we do not want the default artifacts, we can block their creation – Why would I not want it? – E.g., an object should not ever be duplicated by „accident“ Hide the default constructor – Declare in the private part of the class What if not even the class itself may use it? – Declare it in the class => Compiler won‘t create one for you – But never implement it => Linker will complain if you ever use it 31 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Rule of Three The “Rule of Three” states that if you define either of them, you most likely need to define all three of them – Copy Constructor – Assignment Operator – Destructor In any case, follow this rule and even if you do not need the others, just provide the same as the compiler-generated code to show that you did not forget about the others 32 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Friends Allow other functions and classes access to protected and private members Useful for – Functions, operators, etc. that logically belong to a class but cannot be defined as member thereof – Classes having a close relationship to each other 33 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies fraction.h Classes: Friend Example class fraction { friend ostream &operator<<(ostream &os, fraction f); friend istream &operator>>(istream &is, fraction &f); }; fraction.cc ostream &operator<<(ostream &os, fraction f) { os << '(' << f.c << ‘/' << f.d << ')'; return os; } inline void check_char(istream &is, char ch) { char c; is >> c; if(c!=ch) { is.putback(c); is.setstate(ios::badbit); } } istream &operator>>(istream &is, fraction &f) { fraction g; check_char('('); check_char('/'); check_char(')'); return is; is >> g.c; is >> g.d; if(is) f=g; } 34 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: User-Defined Conversions class fraction { public: User-defined conversion // conversion fraction to double operator double() { return (double)c/d; } fraction operator+(fraction b); fraction operator-(fraction b); }; double solve(double p, double q) { return ... } Will invoke our userdefined conversion void foo(fraction &a, fraction &b) { cout << "The result is " << solve(a,b) << endl; // implicit cout << "a+b=" << (double)(a+b) << endl; // explicit } Style-wise, in C++, one should use static_cast<double>(a+b) 35 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Classes: Change Through References class fraction { References as return public: type, BUT be careful // conversion fraction to double operator double() { return (double)c/d; } // references as return value int &counter() { return c; } int &denominator() { return d; } fraction operator+(fraction b); fraction operator-(fraction b); }; That’s how they are used void foo(fraction &a, fraction &b) { cout << "a+b=" << (a+b) << "=" << (double)(a+b) << endl; a.counter()=b.denominator(); Style-wise, in this example, } a.set_counter(b.denominator()) would have been more beautiful. 36 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Namespaces Modular programming Avoid name collisions fraction.h User defined data-types namespace fractions { // … int gcf(int a, int b); int lcm(int a, int b); int swap(int &a, int &b); Namespace declarations need to be repeated again in the corresponding .cc file // … } 37 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Namespaces (cont’d) fraction.h Multiple namespace statements are allowed within a single source file Namespaces may be nested Namespaces may anonymous 38 namespace util { int gcf(int a, int b); int lcm(int a, int b); int swap(int &a, int &b); } namespace fraction { class fraction { … }; } Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Using Namespaces Scoping – :: Operator – Example: util::gcf(foo,bar); Import a single name of a given namespace – using declaration – Example: using NAMESPACE::VAR; Import all names defined in a given namespace – using directive – Example: using namespace NAMESPACE; 39 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Namespaces: Operators Operators can be defined in multiple ways and scopes – As member function: fraction fraction::operator+(complex b); – Stand-alone: fraction operator+(fraction a, complex b); – As stand-alone operator, in the current namespace, or that of fraction, or that of complex Wow! So which one will be used? 40 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Namespaces: Operators Example: fraction a; complex b; cout << a+b << endl; A a; B b; cout << a+b << endl; 1. Does A have a member operator+(b) => yes => use it, if it has multiple, use standard overloading rules 2. Is there an operator+(a,b) defined in the namespace where A or B is defined in? => yes => use it, if it has multiple, use standard overloading rules 41 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Summary Administrative Issues – Prerequisites & Goals – Schedule – Exams & Grading C++ – – – – 42 Introduction (“Hello World”) Functions and Operators Object-Based Programming (Classes and Structures) Namespaces Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 0 Visit your local book store – Check out the books recommended in this lecture and some others – Optional, if you really like one, go for it Install a C++ Compiler – Unix: apt-get/yum … g++ make (if not, check with your distribution) – Windows: install the cygwin tools at least base/bash, devel/gcc-c++ and devel/make (dependencies will be selected automatically) – Apple Users: use Xcode, may be downloaded from Apple Developer Web Site or App Store – Possibly in combination with Eclipse (may simplify debugging) 43 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 0 – Some Pointers First install the C++ Compiler – Install the following packages from www.cygwin.com: shells/bash, devel/gcc-g++, devel/make Eclipse Users – Go to www.eclipse.org and download Eclipse IDE for C/C++ Developers – In the past, eclipse/eclipsec should have been run from your cygwin shell (to ensure that paths are set up correctly) 44 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 1 Implement and run the “Hello World” program from this lecture 45 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 2 Have a look at the two swap routines swap(int&,int&) and c_swap(int*,int*) Let the compiler compile the code but ask the compiler to stop at the assembly stage $ gcc –S –o source.s source.cc Compare the assembly code, what do you observe? How do you interpret the difference? 46 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 3 Implement the comprehensive function example twice – Once with the swap and lcm functions declared inline – Once with those functions declared as normal functions Compile the two programs and generate assembly code How many instructions do the different functions have for the two different versions of the example? How do you interpret the differences? 47 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Exercise 4 Implement a data type for complex numbers – Implement the +, -, *, / operators – Implement the << and >> operators – Provide two test drivers • One that checks based on a few samples that your code is correct • One that interactively lets a user invoke some operations with complex numbers 48 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Next Lecture Separate Compilation in C++ Introduction to C++’s Standard Library 49 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation IBM Research – Zurich Process Management Technologies Questions? Happy Coding… … and see you next Thursday 50 Th. Gschwind. Fortgeschrittene Programmierung in C++. © 2014 IBM Corporation