C++
- Basics
- Objects
- Pointers
- Arrays
- Containers
- Templates
- Classes / Structures
- Inheritance
- Constructors
- Destructors
- STL
- Operators
- Memory Allocation
- Stack vs Heap
- Patterns
- C++ Versions
Bjarne Stroustrup
compiled, low level
not memory safe
“Fifty years of programming language research, and we end up with C++???” Richard A. O’Keefe
#include <iostream>
int main() {
return 0;
}
brew install cppcheck
Poked around. Turns out regex is poorly implemented in a lot of C++ compilers. Heads up if you submit your code to competition judges.
Kivy is no fun. :(
When creating the C++ repo it turned my sifer++ into sifer–. What are you trying to tell me GitHub? :(
Basics
strings - just use string stream
swap(a, b)
sort(begin, end, bool)
Base case Tracking with variables Vector slicing
Hash map unordered_set unordered_map
Objects
You can imagine C++ as C with object-oriented features. The four main features are:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
C++ lets you define your own. You can decide how far you want to abstract the class. You can encapsulate functions into methods. Encapsulations makes your software more modular. This makes it so that if you change one part of that program, only that gets changed rather than the entire software.
Functors are function objects they declare and define operator()
STL provides helper base class templates unary_function and binary_function to facilitate user-defined function objects
Pointers
std::shared_ptr
Arrays
std::vector is a dynamic array that can grow and shrink at the end
supports random access iterators
similar to but more powerful than built-in C/C++ arrays
std::list has constant time insertion and deletion at any point in the sequence (not just at beginning and end)
performance trade-off: does not offer a random access iterator
implemented as doubly-linked list
Containers
STL containers are Abstract Data Types
sequential containers
associative containers
adapters
std::map associates a value with each unique key
std::multiset, std::multimap can support multiple equivalent (non-unique) keys uniqueness is determined by an equivalence relation
Templates
STL Pair Helper Class this template group is the basis for the map and set associative containers because it stores (potentially) heterogeneous pairs of data together
Classes / Structures
- Use of class and struct are largely preferential
- class ThisWorks / struct ThisWorksToo
- Consider scope
- A method in a class is supposed to work on data / attributes of the class.
- Watch how and where you define member fields. Member fields are usually private because they are specific only to that class.
Inheritance
- UML helps a lot. Don’t be lazy and use it.
Constructors
- If for example, 1-2-3 are constructed then the usual order of destruction is 3-2-1.
- Copy constructor (cc) can be called when an object of a class is returned by value.
- Cc when an obj of a class is constructed based on an object of the same class.
- Cc when compiler generates a temp object.
- No guarantee that cc will be called though. The compiler has some control over this, such as in the example of return value optimization.
Destructors
- ~example()
- Destructors can be private
- There can only be one destructor per object
-
Destructors can be virtual
- Copy control is the rule of three (soon to be four, possibly five) - copy constructor, destructor, assignment operator
- Copy constructor is a special constructor for a class / struct that is used to make a copy of an existing instance.
- If you don’t declare a copy constructor, the compiler will give you one implicitly, which means it will give you member wise copy of the source object.
- When dealing with copy controls, remember - assignment operator consist of both the copy constructor and destructor. You will need to create an if branch. If it is itself, then return itself. If not, then destruct then copy construct. Use deep copy.
shallow copy vs deep copy
STL
“The C++ Standard Template Library by Example Webinars”
std::find() std::adjacent_find() std::copy() std::fill() std::replace() std::remove() std::remove_if() std::transform() std::for_each()
STL Generic Algorithms
algorithms operate over iterators rather than containers
each container declares an iterator and const_iterator as a trait
vector and deque declare random access iterators list, map, set, multimap, and multiset declare bidirectional iterators
each container declares factory methods for its iterator type: begin(), end(), rbegin(), rend()
non-mutating, which operate using a range of iterators, but don’t change the data element found mutating, which operate using a range of ietaros, but can change the order of the data elements sorting and sets, which sort or searches ranges of elements and act on sorted ranges by testing vlaues numeric, which are mutating algorithms that produce numeric results
STL algorithms are decoupled from the particular containers they operate on and are instead parameterized by iterators
all containers with the same iterator type can use the same algorithms
instead of writing a search routine for each kind of container, one only write one for each iterator type and apply it to any container this reduces software development effort
since different components can be accessed by the same iterators, just a few versions of the search routine must be implemented
Operators
- STL
- Dot operator (.)
- Pointer operator (->)
- Reference (&)
- Pointer (*)
- ++i vs i++ is pre vs post
- ++i increases i, returns i
-
i++ makes a copy, increases i, and returns the copy (old value)
-
::someVariable is a global namespace from memory, global variable, work for functions too
- Avoid macro / #define (at least in the real world)
- Macros are pre-processed
When doing separate compilation, you need to create a class. You will get two new files. The .h will be the header files is where you create your prototypes. The .cpp file will be where you create your definitions. Use include guard freely.
- Inline functions are processed in later stages of compilation
- Inline functions are generally more reliable than macros. Inline functions can have returns while macros cannot.
When given:
int x = 4; std::cout << x << ++x << x << x++ << x;
Be very, very mindful of the steps / logic / order of execution of the codes. That should result in: 4 5 5 5 6
- Preprocessor
- Literals
- Declarations
- Storage classes
- Statements
- Functions
- Expressions
- Classes
- Templates
- Namespaces
- Memory
- Math
- Assert
- Iostream
- File
- Stream
- Vector
- Map
- Set
- Algorithm
- Iterators
- Chrono
- Thread
- Future
Memory Allocation
Stack vs Heap
// These variables will be allocated on the stack.
int a;
int b[10];
int c = 20;
int d[c];
// The memory for 10 integers is allocated on the heap.
int *ptr = new int[30];
Patterns
Iterator pattern
Iterators are central to generic programming because they are an interface between containers and algorithms
Algorithms typically take iterators as arguments, so a container need only provide a way to access its elements using iterators this makes it possible to write a generic algorithm that operates on many different kinds of containers, even containers as different as a vector and a doubly linked list
input iterators
output iterators
forward iterators
bidirectional iterators
random access iterators
C++ Versions
C++14 updates
- ptr_share
- rvalue reference
- Never use new / delete outside of scope.
- The keyword “friend” is also not needed as much. See “Interactive Panel: Ask Us Anything” [1] on around 1:01.
- Never use raw pointers. Ditto see.
Pre-C++14
- Ranged-based for loop is nice.
- Versions increase by 3 at every major release.
[1] In case the video is ever taken down, here are the people involved: Day 2 - Attendee-driven Q&A with Day 1 and Day 2 speakers: Bjarne Stroustrup, Andrei Alexandrescu, Herb Sutter, Scott Meyers, Chandler Carruth, Sean Parent, Michael Wong, and Stephan T. Lavavej.
cpp
]