Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

Introduction to C++ for Those Somewhat Familiar with C

Used in a bonus session for a C programming class

  • Sé el primero en comentar

Introduction to C++ for Those Somewhat Familiar with C

  1. 1. Introduction to C++ For Those Somewhat Familiar With C MPATE-GE 2617 C Programming for Music Technology Lab Jong Wook Kim jongwook@nyu.edu
  2. 2. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  3. 3. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  4. 4. Background: History of C ◦ In 1970, Bell Labs needed to port Unix from PDP-7 to PDP-11 ◦ Unix, the OS, was written in assembly until those days ◦ The developers wanted to use a language, but there was no suitable one ◦ So Ritchie made one and named it C in 1972, and wrote K&R C book in 1978 ◦ The language feature has been largely fixed since then ◦ C became the language of choice for system programming ◦ People made OS using C (DOS → Windows, BSD → MacOS → iOS, Linux → Android) ◦ Because it is so simple and old, it is so fast Ken Thompson and Dennis Ritchie PDP-7 (1965) PDP-11 (1970) K&R C (1978)
  5. 5. But C Hasn’t Changed for Decades! “Software Crisis” became a thing circa 1970-1980 ◦ Governments and companies worked on large software projects for the first time ◦ Stock exchange, Healthcare, Combat support system, Criminal intelligence, etc. ◦ But realized: building large-scale software is totally different from building hardware ◦ Projects running over-budget and over-time ◦ Software being very inefficient and of low quality ◦ Code difficult to maintain (= spaghetti code) ◦ Projects being unmanageable To overcome the crisis, new methodologies and paradigms emerged ◦ Software Development Process / Project Management ◦ Version Control System ◦ Software Quality ◦ Birth of “Software Engineering” as a discipline
  6. 6. Programming Paradigms C follows imperative, procedural, and structured programming paradigm ◦ Write commands sequentially and organize them in procedures ◦ Organize associated data in structures After the crisis, programmers wanted new features and paradigms ◦ To become more productive in programming, especially in collaboration ◦ To make more robust/efficient programs ◦ To easily develop on new platforms (web, mobile) ◦ Object-Oriented Programming was the most demanded paradigm C is fixed in features and paradigms, so people created more languages ◦ C++ (’83), ObjC (’84), Python (’91), Lua (’93), Java (’95), Ruby (’95), Scala (’04), Swift (’14)
  7. 7. Object-Oriented Programming A paradigm that designs computer programs based on “objects” ◦ Contains structured data (in fields) and associated behaviors (in methods) ◦ OOP designs a program in terms of objects interacting with one another ◦ Keywords: abstraction, encapsulation, inheritance, polymorphism Class ◦ A popular way for a programming language to implement OOP ◦ Class: specifies the data format and available procedures, like a blueprint ◦ Instance: a realization of a class, with specific data (=state). ◦ What can be fields and methods of: Car, Person, Animal, and Radio? C++ was originally called “C with Classes” ◦ Class = struct with associated methods ◦ More on the specific syntax later
  8. 8. Examples class Radio - frequency: Float - volume: Float - playing: Bool - tuner: Tuner - tune(frequency: Float) - set_volume(volume: Float) - play() - stop()
  9. 9. Examples class Radio - playing: Bool - tuner: Tuner - volume: Float - play() - stop() - tune(frequency: Float) - set_volume(volume: Float) class Tuner circuit: Circuit tune(frequency: Float) get_audio(): Audio class Circuit anthenna: Anthenna variable_resistor: Resistor set_resistance(ohm: Float) …
  10. 10. Examples class Mammal - birthday: Date - weight: Float - breathe() - eat(food: Food) class Person - name: String - study() - work() class Dog - name: String - bark() - howl() class Cat - name: String - purr() - meow()
  11. 11. Software Design Patterns Reusable “pattern” of OOP design that can be used in many situations Provides a solution to commonly occurring problems in software design Ways of organizing relations between objects in order to: ◦ Make the program easy to read and maintain ◦ Implement wanted features efficiently ◦ Maximize reusability of the code Out of the scope of this class ◦ But a must-read for all software engineers ◦ One of them will be covered later (iterator pattern)
  12. 12. C++ as a Modernization of C Created by Bjarne Stroustrup in 1983, ideas originating from his PhD thesis ◦ Support Object-Oriented Programming for large-scale software development ◦ Have to be fast in speed, to be used for practical purposes ◦ Mostly a superset of C, because general-purpose, fast, portable, and widely used Philosophy ◦ Driven by real-world problems and should be useful immediately ◦ User-create types need to have the same performance as built-in types ◦ Should fully support any programming style that programmers want ◦ Allowing a useful feature is more important than preventing misuse of it C++ actively adds support for new features and paradigms ◦ While C remains an almost unchanging, minimal, portable, and efficient toolset ◦ A new Draft International Standard in March 2017, to become C++17
  13. 13. Timeline of C++ 1979: Stroustrup starts to work on “C with Classes” in Bell Labs 1983: Renamed to “C++” 1985: The first edition of <The C++ Programming Language> 1989: C++ 2.0 release 1998: The first ISO Standard (C++98) 2003: C++03, bugfixes of C++98 2011: C++11, a major revision 2014: C++14, bugfixes and small improvements on C++11 2017: (planned) C++17, the upcoming major revision
  14. 14. C++ was such a hit Date Estimated Number of Users Oct 1985 500 Oct 1986 2,000 Oct 1987 4,000 Oct 1988 15,000 Oct 1989 50,000 Oct 1990 150,000 Oct 1991 400,000 ◦ Doubled every 7.5 months in 1979-1991 ◦ More than 3 million in 2004
  15. 15. What Makes It So Unique The only language that: ◦ Supports modern programming paradigms necessary for large-scale development ◦ Supports straightforward and zero-overhead integration with C programs and the OS ◦ Still maintains close-to-metal performance ◦ (Feasible alternatives came up only very recently, like Rust, Go, Swift) Many performance-critical large-scale applications are built in C++ ◦ Windows, MacOS, Android, iOS, and many Linux distributions ◦ Almost all major PC/console games ◦ Almost all browsers: Google Chrome, Safari, Internet Explorer, Edge, Firefox ◦ Almost all Adobe products: Photoshop, Illustrator, Premiere, Acrobat ◦ Almost all DAW software: Logic Pro, Pro Tools, Adobe Audition, Ableton Live ◦ All major C/C++ compilers: GCC, Visual C++, Clang ◦ Core of many deep learning libraries: Tensorflow, Caffe, MXNet
  16. 16. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  17. 17. Hello World ◦ C++ Headers are without the .h extension ◦ using namespace std; ◦ A namespace that contains all features of the C++ standard library ◦ No need to prefix functions with library names ◦ <iostream> provides console input/output via cin and cout ◦ Also endl, which outputs a newline and flushes the stream ◦ No need to use the format string ◦ The shift operator << has a different meaning here – Operator Overloading
  18. 18. Namespaces ◦ Either write using namespace std; or use the prefix std:: ◦ Can be nested to multiple depths ◦ Helps organizing functions, variables, and classes
  19. 19. std::cin ◦ >> operator overloading , for console input ◦ No need to use format strings, again
  20. 20. std::string ◦ Is a “class” provided by the C++ Standard Library ◦ Start by assigning a string literal to a string variable, or in C++14, "hello"s ◦ A lot safer than the C way, manipulating strings only in char*
  21. 21. Function Overloading ◦ The actual function called is dependent on the types of the arguments ◦ Called “ad-hoc polymorphism” by some people
  22. 22. New & Delete ◦ C version: relies on library functions ◦ Size calculation ◦ Allocation with malloc() ◦ Type casting ◦ Initialization ◦ Deallocation with free() ◦ C++ version: a language feature ◦ All of the first 4 in one line ◦ Deallocation with delete
  23. 23. New [] & Delete [] ◦ Again, no need to calculate size and typecast manually ◦ new [] and delete[] have to match
  24. 24. Templates ◦ Template functions and template classes are “realized” according to types ◦ One implementation for many types, improving reusability of code ◦ For example: linked list of type T, hash map from type K to V
  25. 25. References ◦ Acts like a pointer, looks like a variable ◦ Avoids pointer insanity (to some degree) ◦ Cannot be NULL, which is a good thing ◦ Necessary for using some C++ features that we will not go into detail ◦ Operator overloading, copy constructor, move constructor
  26. 26. Exception Handling Most C functions use a special return value to indicate an error ◦ -1, errno, etc., usually a number ◦ Inconsistent codes per function ◦ Cannot return other types C++ encourages using exceptions ◦ Throw any variable anywhere ◦ Across function calls ◦ Catch according to the type ◦ Return value can be result type ◦ Fail-fast on the first error Controversy exists on using them
  27. 27. C++11: Lambdas ◦ A function can be created and passed to another function ◦ Cleaner than using function pointers ◦ Higher-order Function: a function that accepts a function(s) as its parameters ◦ An element of “Functional Programming” paradigm
  28. 28. C++11/14: Type Deduction ◦ Type declaration is not necessary wherever compiler can deduce the type ◦ Useful when stating the type is redundant, too obvious, or too verbose
  29. 29. More Non-OOP Features No Need to typedef struct Single-line comments using // Boolean type bool is a built-in type ◦ no need to include stdbool.h Default arguments: ◦ void foo(int a = 3) { ... Inline functions ◦ Compiler puts the content in the caller, not making a function actually nullptr instead of NULL which is just 0 ◦ Which is number, not a pointer, thus confusing and dangerous
  30. 30. Summary So Far Added features to write programs in safer and more convenient ways Fixing common pain points and incorporating latest paradigms quickly At the cost of having to continuously learn new concepts and paradigms
  31. 31. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  32. 32. Reminder: Object-Oriented Programming A paradigm that designs computer programs based on “objects” ◦ Contains structured data (in fields) and associated behaviors (in methods) ◦ OOP designs a program in terms of objects interacting with one another ◦ Keywords: abstraction, encapsulation, inheritance, polymorphism Class ◦ A popular way for a programming language to implement OOP ◦ Class: specifies the data format and available procedures, like a blueprint ◦ Instance: a realization of a class, with specific data (=state). C++ was originally called “C with Classes” ◦ Class = struct with associated methods ◦ More on the specific syntax later
  33. 33. Class = Data + Behaviors = Struct + methods Methods can be added to a struct ◦ Also known as member functions ◦ Should be associated with the struct’s data ◦ Therefore the task is a “duty” of this class ◦ Yes, A struct with methods is now a class
  34. 34. Terms Class (which is a Type) Field Member Variable Method Member Function
  35. 35. Constructor In the previous example, the initialization of Person’s fields was done in main() ◦ But organizing its fields should be Person’s duty Constructor does that job ◦ Called only as soon as the instance is created ◦ Parameters = any data required for initialization There can be more than one constructors ◦ One of them must be called, otherwise compile fails Can be called during declaration ◦ auto p = new Person(“Doe”) also works
  36. 36. An Even Better Constructor Passes the argument to the string name’s constructor. ◦ Which initializes the string class with the given argument ◦ The no-agrument constructor of string name is never called. In main(), Person is reused ◦ Providing an abstraction ◦ By grouping data (name) and behavior (printing name) inside an object.
  37. 37. Encapsulation: access specifier Fields and methods can have “access specifiers”, e.g. public: or private:
  38. 38. Encapsulation: accessor Accessor (or getter) method ◦ Simply returns a field ◦ Allows others to see the value ◦ But not mutate the value ◦ Read-only for others, full access for self Abstraction to users of the class Person ◦ Only need to know ◦ The methods and constructors of the class ◦ No need to know ◦ Any private fields or methods
  39. 39. struct vs class The only difference is the default access level ◦ Members of struct are public by default ◦ Members of class are private by default In C, struct was just a data bundle ◦ That can be manipulated from anywhere C++ added methods to struct for class ◦ struct members have to be public by default ◦ To retain compatibility with C ◦ But C++ liked encapsulation so much! ◦ So they made class members private by default Rule of thumb ◦ Use struct for simple data storage ◦ May have minimal logic on data validation, etc. ◦ Use class for anything more than that
  40. 40. Inheritance – Basics Derived class inherits base class ◦ Student = Derived, Person = Base ◦ Derived class has all members of Base Makes it easier to ◦ Reuse the functionality of the base class
  41. 41. Inheritance – Pet Example talk() inherited to Dog and Cat: sound() overridden in Dog and Cat If base class has a constructor ◦ Must call when constructing derived ◦ Unless base constructor is zero-argument Use virtual method if inheriting ◦ Required for polymorphism
  42. 42. Polymorphism The pets example continued: ◦ void print(Pet &) does not know anything about the two derived classes ◦ Compiler does not consider the derived classes at all, while compiling this function ◦ Still the corresponding sounds gets printed. ◦ Because the exact method to be called is determined during the run-time ◦ virtual keyword is required for this process ◦ Single interface talk() can invoke many different implementations depending on the type ◦ Thus called “polymorphic”
  43. 43. Pure Virtual Methods ◦ We didn’t need the function returning “???”, and we can just put =0 instead ◦ This method has no definition, and is called a pure virtual method ◦ A class with a pure virtual method is called an abstract class, as opposed to a concrete class ◦ An abstract class cannot be instantiated directly, and derived types must be used ◦ A derived type must override all pure virtual methods, otherwise it becomes abstract too
  44. 44. Access Specifier: protected Protected members are accessible only from a derived class public protected private this class Yes Yes Yes derived classes Yes Yes No elsewhere Yes No No
  45. 45. Destructor Class may manage resources ◦ e.g. files, connections to web ◦ malloc’ed memory buffer ◦ Resource handles, like SNDFILE * ◦ that have to be cleaned up / closed Destructor is responsible of ◦ Safely closing any open resources Called when object’s lifetime ends ◦ A local variable gets out of scope ◦ An object is delete’ed ◦ Program exits (global variables)
  46. 46. RAII Acronym for Resource Acquisition Is Initialization Resource usage is encapsulated in the lifetime of an object ◦ Constructor acquires the resource or throws an exception when it cannot ◦ Destructor releases the resource and never throws exceptions Using the resource is always through an instance of a RAII-class ◦ Guarantees that the resource is available, whenever an instance is reachable ◦ Prevents unwanted access to resources after being released ◦ Makes sure to release the resource properly To make the most out of RAII, ◦ Limit the scope of a variable to where it is actually being used ◦ When it is dynamically allocated, be sure to delete
  47. 47. std::fstream A good example of RAII ◦ File is closed as fstream exits the scope A good example of polymorphism The same function print() works on both console output and file output Replaces fopen/fprintf/fclose
  48. 48. Summary of OOP Concepts Abstraction ◦ In many levels, of data (encapsulation), hierarchy (inheritance), behavior (polymorphism) Encapsulation ◦ Information hiding, with private, protected, or public access specifiers ◦ Provide users only what they need to know, to make it easier to use and prevent misuse Inheritance ◦ Subclass can extend base class inheriting its data and behavior ◦ Can build a hierarchy of classes, representing “is a” relationships Polymorphism ◦ Behavior of a method can be different, depending on the subclass
  49. 49. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  50. 50. The Standard Template Library In C, the closest thing that we had to a data structure is array of structs So we had to implement our own as we go ◦ Queue of visited cells for breadth-first search in a maze ◦ Hash map for searching phone book by the last name ◦ Linked list of phone book entries, using chain parameter However, the implementation had to be specific to the element type ◦ There is void *, but it throws away any type information and safety STL allows a generic implementation regardless of types, using templates ◦ e.g. queue<Cell>, map<string, PhoneBookEntry>, list<PhoneBookEntry>
  51. 51. Containers There are a lot of data structures made for storing collection of data ◦ Sequence containers ◦ vector, array, list, forward_list ◦ Each has different efficiency for random access, insertion, and deletion ◦ Sequence container adapters ◦ stack, queue, priority_queue ◦ Ordered associative containers ◦ set, map, multiset, multimap ◦ Unordered associative (hash) containers ◦ unordered_set, unordered_map, unordered_multiset, unordered_multimap In C, had to go with own implementation always ◦ There is no de-facto standard containers library or something close to that ◦ Partly due to the lack of templates
  52. 52. std::vector<T> Like a regular array, but resizes dynamically as needed Capacity can be given in constructor or by reserve() Suitable for append-only seq of unknown length with index access
  53. 53. std::array<T, N> Contains a fixed-length array ◦ Same performance as C array, as it does not dynamically allocate memory Conforms with other STL containers ◦ Supports size(), front(), back() etc. ◦ Can produce iterators, to be covered later
  54. 54. std::list<T> Implementation of doubly-linked list Compared to vector/array ◦ Faster insertion in the middle ◦ No spurious delay for insertion due to reallocation ◦ Same O(n) complexity for sequential traverse ◦ Relatively inefficient memory usage overall ◦ O(n) random access, as opposed to vector/array’s O(1)
  55. 55. std::forward_list<T> Does not have “backwards” link ◦ Can only traverse from the beginning, which is enough for many use cases ◦ Same time complexity for insertion, deletion, traversal, random access ◦ Slightly higher memory efficiency ◦ No size(), back(), push_front() available – have to use iterators
  56. 56. std::stack<T> First-in, last-out data structure ◦ push(), pop(), top() ◦ Can optionally replace the back-end data structure ◦ Anything that supports push_back(), pop_back(), and back().
  57. 57. std::queue<T> First-in, first-out data structure ◦ push(), pop(), top() ◦ Can optionally replace the back-end data structure
  58. 58. std::priority_queue<T> Constant-time lookup of the largest element Other criteria can be given as the third template argument
  59. 59. std::set<T> Contains a set of unique items ◦ Efficient for checking existence of items, number of unique items std::set<T>: based on binary search tree ◦ Automatically sorts the items, logarithmic time lookup std::unordered_set<T>: based on hash ◦ Not ordered, constant time lookup
  60. 60. std::map<K, V> Associative container – retrieve a value associated with given key std::map<K, V>: based on binary search tree ◦ Automatically sorts the items based on key, logarithmic time lookup std::unordered_map<K, V>: based on hash ◦ Not ordered, constant time lookup
  61. 61. Iterators A generalization of pointer for traversing containers ◦ Used as a common interface for different container types
  62. 62. Iterators: range-based for loop Having a unified interface for traversing containers enables this: One less variable to think about (the index) ◦ One less source of possible bugs
  63. 63. Iterators: find() Searches a container and returns an iterator pointing to the found item ◦ or container.end() if not found std::find() performs the same job ◦ Also usable for containers with non-constant time lookup
  64. 64. Algorithms std::find() is one of the functions in the algorithms library In C, there were only two: qsort and bsearch Curated list of C++ algorithms ◦ for_each, count, find, search ◦ copy, fill, transform, generate, swap, reverse, rotate, shuffle, unique ◦ is_sorted, sort, partial_sort, stable_sort, nth_element ◦ is_heap, make_heap, push_heap, pop_heap ◦ max, max_element, min, min_element, minmax, minmax_element ◦ is_permutation, next_permutation, prev_permutation ◦ accumulate, inner_product, adjacent_difference, partial_sum, reduce
  65. 65. Algorithms: for_each Yet another way of visiting all elements in a container Range-based-for is shorter, but useful when we want to: ◦ Apply a function to a partial range ◦ Apply a function that is already implemented somewhere else
  66. 66. Algorithms: Permutations Prints all possible permutations in a range of items
  67. 67. std::shared_ptr Dynamically allocated objects are useful when an instance is ‘shared’ ◦ So having it as a local variable is not very feasible But having to remember and control exactly when to delete them is difficult! ◦ Difficult also means dangerous ◦ Continuing the “making it harder to shoot yourself in the foot” philosophy ◦ References to an object is counted, and gets deleted automatically when it reaches 0 ◦ Can be used just like regular pointers Similar: std::unique_ptr ◦ Instead of reference counting, only one pointer can own the access
  68. 68. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  69. 69. The SOLID Principles A mnemonic acronym for 5 basic principles of OOP design Single Reponsibility Principle ◦ A class should have only a single responsibility Open/Closed Principle ◦ Software entities should be open for extension, but closed for modification Liskov Substitution Principle ◦ Objects should be replaceable with a subtype without altering the correctness Interface Segregation Principle ◦ Many client-specific interfaces are better than one general-purpose interface Dependency Inversion Principle ◦ One should depend upon abstractions, not concretions
  70. 70. Single Responsibility Principle A class should have only one responsibility which ◦ Should be entirely encapsulated by the class ◦ Should be apparent by looking at the name ◦ Robert C Martin: “A class should have only one reason to change” Good example ◦ A report printer program may have two reasons to change, thus has ◦ A class representing the content of a report ◦ A class representing the format of a report Bad example ◦ There is only one big class that basically have all functions of a program ◦ Just like C, but inside a class!
  71. 71. Open-Closed Principle Open for extension ◦ The behavior of a base class can be extended (usually via inheritance) Closed for modification ◦ Modification of the base class is not desired
  72. 72. Liskov Substitution Principle Code written for a base class should also work when an instance of a derived class
  73. 73. Interface Segregation Principle Interfaces ◦ Usually means a class with only pure virtual functions C++ Supports multiple inheritance ◦ Segregate interfaces to the simplest unit ◦ Multiple inheritance for a versatile class
  74. 74. Dependency Inversion Principle main() Task1 Subtask1-1 Subtask1-2 Task2 Subtask2-1 Subtask2-2 Task3 Subtask3-1 Subtask3-2
  75. 75. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  76. 76. PortAudio C++
  77. 77. PortAudio C++ Continued
  78. 78. Eigen Fast linear algebra library entirely based on templates ◦ brew install eigen
  79. 79. Other Notable C++ Libraries
  80. 80. Things To Be Covered 1. History and Philosophy of C++ 2. Language Features Besides Object-Orientation 3. Object-Oriented Programming in C++ 4. The C++ Standard Template Library 5. The SOLID Principles 6. Examples of Using C++ Libraries 7. Summary
  81. 81. Summary C++ as a whole package ◦ Provides tons of modern facilities for programmers to utlize ◦ Object-Oriented Programming ◦ Functional Programming ◦ Generic Programming ◦ Don’t be scared, just pick any subset you would like ◦ More library options that will help you explore ideas ◦ In some sense, C++ is the final boss of programming languages

×