You are on page 1of 9

#+SETUPFILE: ..

/setup1
#+TITLE: Programmazione ad oggetti
# 147
# Lesson 5
* Resources
** Recommended W flags
~-Wall~ ~-Wextra~
* Basic C++
** Tidbits
*** Comma operator
evaluates left expression, discard, than return the right one
*** Dangling Else
~else~ get matched to the closer unmatched ~if~
*** Stdint.h
#+BEGIN_SRC c++
#include <stdint.h>
int32_t x;
uint32_t y;
int64_t z;
#+END_SRC
*** Numeric Limits
#+BEGIN_SRC c++
#include<limits>
numeric_limits<long int>::max();
numeric_limits<long int>::epsilon(); // returns the difference between 1.0 and t
he next possible value
#+END_SRC
** Literal Prefixes/Suffixes
*char prefixes*
- u :: unicode16 char_16t
- U :: unicode32 char_32t
- L :: wide wchar_t
- u8 :: utf-8, only strings
*number suffixes*
- U :: Unsigned
- L :: Long
- F :: Float
- Double is the defualt for decimals
** Top and Low level const
A const pointer is called *top level*.
A pointer to const is called *low level*.
#+BEGIN_SRC c++
const int *p1; // low-level const
int *const p2; // top-level const
#+END_SRC
** dynamic arrays
#+BEGIN_SRC c++
int *board = new int[size];
delete [] board;
#+END_SRC
Dynamic multidimensional arrays.
#+BEGIN_SRC C++
int** board = new int*[boardSize];
for(int i = 0; i < boardSize; ++i)
board[i] = new int[boardSize];
for(int i = 0; i < regionSize; ++i)
delete board[i];
delete board;
#+END_SRC
** Strings
#+BEGIN_SRC c++
str.empty();
#+END_SRC
Strings comparison
#+BEGIN_SRC c++
"Hello" < "Hello World" < "Hiya";
#+END_SRC
#+BEGIN_SRC c++
stringa.c_str();
#+END_SRC
** Cctype
- isalnum :: Check if character is alphanumeric (function )
- isalpha :: Check if character is alphabetic (function )
- isblank :: Check if character is blank (function )
- iscntrl :: Check if character is a control character (function )
- isdigit :: Check if character is decimal digit (function )
- isgraph :: Check if character has graphical representation (function )
- islower :: Check if character is lowercase letter (function )
- isprint :: Check if character is printable (function )
- ispunct :: Check if character is a punctuation character (function )
- isspace :: Check if character is a white-space (function )
- isupper :: Check if character is uppercase letter (function )
- isxdigit :: Check if character is hexadecimal digit (function )
- tolower :: Convert uppercase letter to lowercase (function )
- toupper :: Convert lowercase letter to uppercase (function )
** Cstring
- strlen(p) ::
- strcmp(p1, p2) :: return 0 if equals, positive if p1 > p2, negative otherwise
- strcat(p1, p2) :: append p2 to p1, returns p1
- strcpy(p1, p2) :: copies p2 to p1, return p1
** Reference and pointers to arrays
#+BEGIN_SRC c++
int (*p)[10] = &array; //pointer to an int[10]
int (&r)[10] = array; //reference to an int[10]
#+END_SRC
** Operators precedence and associativity
[[file:images/po_precedence.png]]
** Implicit Type Conversions
#+BEGIN_SRC c++
bool flag; char cval;
short sval; unsigned short usval;
int ival; unsigned int uival;
long lval; unsigned long ulval;
float fval; double dval;
3.14159L + 'a'; // 'a' promoted to int, then that int converted to long double
dval + ival; // ival converted to double
dval + fval; // fval converted to double
ival = dval; // dval converted (by truncation) to int
flag = dval; // if dval is 0, then flag is false, otherwise true
cval + fval; // cval promoted to int, then that int converted to float
sval + cval; // sval and cval promoted to int
cval + lval; // cval converted to long
ival + ulval; // ival converted to unsigned long
usval + ival; // promotion depends on the size of unsigned short and int
uival + lval; // conversion depends on the size of unsigned int and long
#+END_SRC
** Explicit Type Conversions
#+BEGIN_SRC c++
static_cast<Type>(expression)
static_cast<double>(intval)
#+END_SRC
*Advice: Avoid Casts* in general.
We can only change low level const with ~const_cast~, however if we
remove a const to an object that originally wasn't const, the result
is undefined.
#+BEGIN_SRC c++
const int* p = &r;
const_cast<int*> (p);
#+END_SRC
With ~reinterpret_cast~ you can do any conversion you want, even if it makes no
sense.
** Pointer to function
#+BEGIN_SRC c++
bool (*pf)(const string &, const string &);
pf = orig_function; // no need for &
pf(a, b); // no need for deferencing
#+END_SRC
We can declare and use functions as parameters without declaring them
as pointers, they will get converted automatically.
But we must explictly say they are pointers when we need to return them
** Sequential Containers
*** Containers
- ~list~ :: double linked list
- ~forward_list~ (11) :: single linked list
- ~deque~ :: x random access container, but with fast insert and erase at the be
ginning and at the end.
*** Copy & Swap
To copy directly a container, container and item types must match.
Or, you can copy with two iterators, and just the items have to match.
#+BEGIN_SRC c++
deque dq(ls.begin(), ls.end());
// or
dq.assign(ls.begin(), ls.end());
#+END_SRC
*Swap*
Container and item types must match
#+BEGIN_SRC c++
swap(c1, c2);
#+END_SRC
*** Modifiers
- ~insert~ :: ~(it, element), (it_where, beg_it, end_it), (it, 10, element)~
it returns an iterator to the first of the newly inserted values
- ~erase~ ::
- ~push_back~ ::
- ~pop_back~ ::
- ~push_front~ ::
- ~pop_front~ ::
- ~clear~ :: empty the container
*C++11*
- ~emplace~ ::
- ~emplace_back~ ::
- ~emplace_front~ ::
*** List Operations
Only for ~list~ and ~forward_list~:
- ~splice~ :: transfer values from another list into position ~(iterator positio
n, list& x)~, ~(iterator position, list& x, beg, end)~
- ~remove~ :: remove if values is equal to ... ~remove(30)~
- ~remove_if~ :: ~remove_if(predicate_function)~
- ~unique~ :: removes all but the first element from every consecutive group of
equal elements in the container
- ~merge~ :: ~merge(list &x)~ both containers should already be sorted, it trans
fer all elements from x in their right order
- ~sort~ ::
- ~reverse~ ::
*** Safe Access
#+BEGIN_SRC c++
vector<int> vec;
cout << vec[0] // run-time error
cout << vec.at(0) //throws out_of_range exception
#+END_SRC
*** Manage Capacity
#+BEGIN_SRC c++
c.shrink_to_fit();
c.capacity();
c.reserve();
#+END_SRC
** Set and Map
#+BEGIN_SRC c++
map<string, int> m;
m["test"] = 3;
for(map<string, int>::iterator it = m.begin(); it != m.end(); ++it) {
it->first; // it returns a pair, where you can access key
and value
m.erase(key);
#+END_SRC
#+BEGIN_SRC c++
#include<utility>
pair<int, int> c;
c.first; c.second;
#+END_SRC
#+BEGIN_SRC c++
#include<set>
set<int> s;
s.insert(v.begin(), v.end());
s.insert(value); // it returns a pair, the second value is a
//bool telling us if the value was inserted or not
#+END_SRC
** Algorithms
#+BEGIN_SRC c++
#include<iterator>
back_inserter(someVector); //returns the back inserter
inserter(someSet, someSet.end()) //for sets, or if you want to insert at a s
pecific position
#include<numeric>
accumulate(beg,end, 0) // sum all starting from 0
#include<algorithm>
find(); find_if();
count(); count_if();
copy(beg, end, beg_other);
replace(b,e,0,42);
reverse(b,e);
//all_of(); any_of(); //! C++11!
for_each();
mismatch(); // first value that is not equal
equal();
next_permutation(b,e, compare = operator<); //return false if already at max
min_element(); // returns an iterator
max_element();
remove(); // returns new past the end iterator
remove_if();
partition();
stable_partition();
set_union(a.b, a.e, b.b, b.e, inserter);
set_difference(a.b, a.e, b.b, b.e, inserter);
lower_bound(b, e, value);
upper_bound(b, e, value);
#+END_SRC
* Classes
** Static functions and members
#+BEGIN_SRC c++
class SomeClass {
static int nOfObjects; // there will only be one instance of this var
iable for all the objects
static int get_nofobjects(); // this function can be called even without a
n object
#+END_SRC
Static data members are usually initialized in =Class.cpp= file,
#+BEGIN_SRC c++
// in Account.cpp
double Account::interestRate = initRate(); // notice that ~initRate()~ is a pr
ivate function of the class.
#+END_SRC
** Mutable
Mutable data members can be changed even if the object is const:
#+BEGIN_SRC c++
mutable int altezza;
#+END_SRC
** Functions that return this
When you want to concatenate like this ~Screen.set().move()~
#+BEGIN_SRC c++
Screen &Screen::set() { // notice the & so that we can use as an lvalu
e
return *this;
}
#+END_SRC
If we want this to work with const object we need to overload the function as co
nst and non const version.
#+BEGIN_SRC c++
const Screen &Screen::set() const {
return *this;
}
#+END_SRC
** Friends
Friends can be both *functions* and *classes*.
All members of a class friend can access the private members of the class granti
ng friendship.
_When we *define* a friend function inside a class, *we have to still declare it
* outside it._
** Implicit conversion
Constructors with single arguments define implicit conversions from argument typ
e to class type.
we can prevent this by defining the constructor as explicit:
#+BEGIN_SRC c++
explicit Person(string);
#+END_SRC
** Assignment operator
It should return a reference to operand on the left side.
#+BEGIN_SRC C++
Class &operator=(const &Class) {
return *this;
}
#+END_SRC
In case we are dealing with dynamic memory:
_We should deal with the case of *self assignment*._
#+BEGIN_SRC c++
Class &operator=(const &Class orig) {
string *tmp = new string(*orig.str);
delete str;
str = tmp;
return *this;
}
#+END_SRC
** Rule of 3
A class that needs a destructor, almost certainly needs to define *copy construc
tor* and *copy assignment*.
** How to prevent copies
We declare the methods as private, but not define them.
Attempt to use them by user is going to fail at compile time. Attempt to use by
friends is going to fail at link time.
#+BEGIN_SRC c++
class Class {
private:
Class(const &Class);
Class &operator=(const &Class);
}
#+END_SRC
** Pointer like classes
The copy assignment operator should work like this:
#+BEGIN_SRC c++
Class &operator= (cosnt &Class right) {
++*right.cnt;
if (--*cnt == 0) {
delete cnt;
delete str;
}
cnt = right.cnt;
str = right.str;
return *this;
}
#+END_SRC
* Inheritance
** Derived Class Constructor
The base part of the object is initialized by the base constructor
#+BEGIN_SRC c++
Bulk_quote(const string& book, double p, size_t qty, double disc) : Quote(book
, p), min_qty(qty), discount(disc) { }
#+END_SRC
** Virtual Functions
Once a function is declared as virtual it remains virtual in all the derived
classes. So there is no need to repeat the keyword ~virtual~
** Access Controls
derived class members can access protected member of its base class that are par
t of its derived class. Not protected members of pure base class.
_Access to the members of a base class is controlled by the access specifiers in
the base class itself_
_The purpose of the *derivation acess specifier* is to control the ccess that *u
sers* of the derived class ahve to members inherited from Base_
The derivation access specifier used by a derived class also control acehcess fr
om classes that inherit from that derived class.
** Accessiblity of Derived-to-base conversion
For any given point in your code, if a public member of the base class would be
accesssbile the the derived-to-base conversion is also accessible.
** Constructors and copy control
The *denstructor* must be ~virtual~ because when managing dynamic memory through
a pointer of base class, the right destructor still needs to be called.
The *copy constructor*:
#+BEGIN_SRC c++
D(const D& d): Base(d), /* initializers for D members */ { }
#+END_SRC
The *assignment operator*:
#+BEGIN_SRC c++
D &D::operator=(const D &rhs) {
Base::operator=(rhs);
// D related assignments and memory managment
return *this;
}
#+END_SRC

You might also like