\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{dev.faffo} \pdfinfo{ /Title (c-cheatsheet-class-object-oriented-programming.pdf) /Creator (Cheatography) /Author (dev.faffo) /Subject (C++ Cheatsheet, Class Object-Oriented Programming Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{5C6BC0} \definecolor{LightBackground}{HTML}{F4F5FB} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{C++ Cheatsheet, Class Object-Oriented Programming Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{dev.faffo} via \textcolor{DarkBackground}{\uline{cheatography.com/211140/cs/45677/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}dev.faffo \\ \uline{cheatography.com/dev-faffo} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 16th February, 2025.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Suddivisione tra file .h e .cpp}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{File Header (.h)}} \newline % Row Count 1 (+ 1) Contiene la dichiarazione della classe, ovvero la sua interfaccia pubblica e privata. In questo file si definiscono gli attributi e i prototipi delle funzioni membro. \newline % Row Count 5 (+ 4) {\bf{File di Implementazione (.cpp)}} \newline % Row Count 6 (+ 1) Contiene il codice effettivo delle funzioni dichiarate nel file .h. Qui vengono implementati i metodi della classe.% Row Count 9 (+ 3) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Person.h}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#ifndef PERSON\_H \newline \#define PERSON\_H \newline \newline \#include \textless{}string\textgreater{} \newline \newline class Person \{ \newline private: \newline std::string name; \newline int age; \newline \newline public: \newline // Constructor \newline Person(std::string n, int a); \newline \newline // Getter methods \newline std::string getName() const; \newline int getAge() const; \newline \newline // Setter methods \newline void setName(std::string n); \newline void setAge(int a); \newline \newline // Display method \newline void display() const; \newline \}; \newline \newline \#endif} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Utilizzo di header guard per evitare che il file venga incluso più volte} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Person.cpp}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include "Person.h" \newline \#include \textless{}iostream\textgreater{} \newline \newline // Constructor \newline Person::Person(std::string n, int a) : name(n), age(a) \{\} \newline \newline // Getter methods \newline std::string Person::getName() const \{ \newline return name; \newline \} \newline \newline int Person::getAge() const \{ \newline return age; \newline \} \newline \newline // Setter methods \newline void \seqsplit{Person::setName(std::string} n) \{ \newline name = n; \newline \} \newline \newline void Person::setAge(int a) \{ \newline age = a; \newline \} \newline \newline // Display method \newline void Person::display() const \{ \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} name \textless{}\textless{} ", Age: " \textless{}\textless{} age \textless{}\textless{} std::endl; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{main.cpp}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \#include "Person.h" \newline \newline int main() \{ \newline // Create an instance of Person \newline Person p1("Alice", 25); \newline \newline // Display initial values \newline p1.display(); \newline \newline // Modify attributes \newline p1.setName("Bob"); \newline p1.setAge(30); \newline \newline // Display updated values \newline p1.display(); \newline \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Name: Alice, Age: 25 \newline Name: Bob, Age: 30 \newline Name: Charlie, Age: 20 \newline Student ID: 12345} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Incapsulamento}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{L'incapsulamento è il principio OOP che {\bf{nasconde l'implementazione}} di una classe e fornisce un'{\bf{interfaccia pubblica}} per interagire con essa. \newline % Row Count 3 (+ 3) ✔ Protegge i dati dall'accesso non autorizzato. \newline % Row Count 4 (+ 1) ✔ Permette di modificare l'implementazione senza cambiare l'interfaccia pubblica. \newline % Row Count 6 (+ 2) ✔ Aumenta la modularità e la manutenibilità del codice.% Row Count 8 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Tipo di Dato Astratto (ADT - Abstract Data Type)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Un {\bf{Tipo di Dato Astratto (ADT)}} è un modello di dati che {\bf{definisce solo il comportamento}} (interfaccia) senza rivelarne i dettagli interni. \newline % Row Count 3 (+ 3) {\bf{ADT}} → Descrive solo cosa fa una struttura dati, senza preoccuparsi di come è implementata. \newline % Row Count 5 (+ 2) {\bf{Incapsulamento}} → Protegge i dati interni e li rende accessibili solo attraverso metodi controllati.% Row Count 8 (+ 3) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Membri di una classe}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{I {\bf{membri di una classe}} sono le componenti che definiscono le sue caratteristiche e il suo comportamento. Si dividono in due categorie principali: \newline % Row Count 3 (+ 3) {\bf{Membri Dati (Attributi)}} \newline % Row Count 4 (+ 1) Sono le variabili che rappresentano lo stato dell'oggetto. \newline % Row Count 6 (+ 2) {\bf{Membri Funzione (Metodi)}} \newline % Row Count 7 (+ 1) Sono le funzioni che definiscono il comportamento della classe, operando sui suoi membri dati.% Row Count 9 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Specificatori di accesso}} \newline {\emph{private}}: accessibili solo all'interno della classe. \newline {\emph{protected}}: accessibili nella classe e nelle sue derivate. \newline {\emph{public}}: accessibili da qualsiasi parte del programma.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Specificatori di accesso predefiniti}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{La differenza principale tra `struct` e `class` riguarda gli {\bf{specificatori di accesso predefiniti}}: \newline % Row Count 3 (+ 3) - `struct` → Accesso predefinito: public \newline % Row Count 4 (+ 1) - `class` → Accesso predefinito: private% Row Count 5 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Scope delle Classi}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{Scope (ambito)}} di una classe determina {\bf{dove e come}} i suoi membri possono essere accessibili e utilizzati. Il concetto di scope è fondamentale per gestire la visibilità e l'organizzazione del codice. \newline % Row Count 5 (+ 5) Dentro una classe, i membri possono essere definiti con tre {\bf{specificatori di accesso}}: \newline % Row Count 7 (+ 2) - public → Accessibile ovunque nel programma. \newline % Row Count 8 (+ 1) - protected → Accessibile solo dalle classi derivate. \newline % Row Count 10 (+ 2) - private → Accessibile solo all'interno della stessa classe. \newline % Row Count 12 (+ 2) Le classi possono essere definite dentro uno {\bf{spazio dei nomi (namespace)}} per organizzare meglio il codice ed evitare conflitti.% Row Count 15 (+ 3) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Metodi Interni}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{I metodi sono definiti direttamente all'interno della dichiarazione della classe nel file header (`.h`). \newline % Row Count 3 (+ 3) ✅ Vantaggi: Il compilatore può ottimizzare il codice (inline). \newline % Row Count 5 (+ 2) ❌ Svantaggi: Il file header diventa più grande e potrebbe causare ricompilazioni non necessarie.% Row Count 7 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Se sono semplici e corti, per sfruttare la compilazione `inline`.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Metodi Esterni}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{I metodi sono dichiarati nel file header (`.h`) ma implementati separatamente in un file `.cpp`. \newline % Row Count 2 (+ 2) ✅ Vantaggi: Migliora la separazione tra dichiarazione e implementazione, riduce la necessità di ricompilazione. \newline % Row Count 5 (+ 3) ❌ Svantaggi: Il compilatore potrebbe non ottimizzarli come funzioni inline.% Row Count 7 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Se sono più complessi o se si vuole mantenere il codice più organizzato.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Membro statico}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{class Counter \{ \newline public: \newline static int count; // Membro statico (condiviso) \newline \}; \newline \newline int Counter::count = 0; // Definizione del membro statico} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Metodo virtuale}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Un {\bf{metodo virtuale}} è un metodo dichiarato nella classe base con la parola chiave `virtual`, che può essere {\bf{sovrascritto}} nelle classi derivate. Permette il {\bf{polimorfismo dinamico}}, in modo che, quando viene chiamato tramite un puntatore o un riferimento alla classe base, venga eseguita l'implementazione della classe derivata, se presente. Questo meccanismo consente di definire comportamenti diversi a seconda del tipo reale dell'oggetto.% Row Count 10 (+ 10) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Membri Speciali}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Costruttori: inizializzano gli oggetti della classe.} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Operatori sovraccaricati: ridefiniscono operatori standard (`+`, `=`, `\textless{}\textless{}`, ecc.).} \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Costruttore di copia (`ClassName(const ClassName\& other)`)} \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Operatore di assegnazione (`ClassName\& operator=(const ClassName\& other)`)} \tn % Row Count 8 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Distruttore (`\textasciitilde{}ClassName()`)} \tn % Row Count 9 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Costruttore di spostamento \seqsplit{(`ClassName(ClassName\&\&} other) noexcept`)} \tn % Row Count 11 (+ 2) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Operatore di assegnazione per spostamento (`ClassName\& operator=(ClassName\&\& other) noexcept`)} \tn % Row Count 13 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Funzione Membro `combine` come operatore `+=`}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Counter \{ \newline private: \newline int value; \newline \newline public: \newline // Costruttore \newline Counter(int v = 0) : value(v) \{\} \newline \newline // Funzione membro combine() in stile += \newline Counter\& combine(const Counter\& other) \{ \newline this-\textgreater{}value += other.value; // Aggiunge il valore dell'altro oggetto \newline return *this; // Restituisce l'oggetto stesso \newline \} \newline \newline // Metodo per visualizzare il valore \newline void display() const \{ \newline std::cout \textless{}\textless{} "Value: " \textless{}\textless{} value \textless{}\textless{} std::endl; \newline \} \newline \};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{La funzione membro `combine()` può essere progettata per modificare l'oggetto stesso e restituire una referenza ad esso, proprio come l'operatore `+=`.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Name Lookup}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Il {\bf{name lookup}} (ricerca dei nomi) è il processo con cui il compilatore trova la dichiarazione di una variabile, funzione o classe. Questo meccanismo è fondamentale per comprendere come vengono risolti i nomi nei diversi scope e nei contesti di {\bf{ereditarietà, namespace e classi annidate}}. \newline % Row Count 6 (+ 6) Nelle classi, il compilatore cerca i nomi in questo ordine: \newline % Row Count 8 (+ 2) 1️⃣ Classe derivata \newline % Row Count 9 (+ 1) 2️⃣ Classe base \newline % Row Count 10 (+ 1) 3️⃣ Namespace globale (se necessario)% Row Count 11 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{La ricerca dei nomi segue la {\bf{regola dell'ambito più vicino (scope resolution)}}: \newline 1️⃣ Il compilatore cerca il nome {\bf{nel blocco locale}}. \newline 2️⃣ Se non lo trova, cerca negli {\bf{scope superiori (funzione, classe, namespace)}}. \newline 3️⃣ Se non esiste nel file, dà un {\bf{errore di compilazione}}.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Membri di Tipo Puntatore}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline private: \newline std::string{\emph{ name; // Puntatore a una stringa dinamica \newline \newline public: \newline // Costruttore \newline Person(const std::string\& n) \{ \newline name = new std::string(n); // Allocazione dinamica \newline \} \newline \newline // Distruttore \newline \textasciitilde{}Person() \{ \newline delete name; // Libera la memoria \newline \} \newline \newline void display() const \{ \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} }}name \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline Person p("Alice"); \newline p.display(); \newline return 0; // Il distruttore libera la memoria \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Sono utilizzati per gestire {\bf{risorse dinamiche}} come memoria allocata su heap, file, socket, ecc. Se non gestiti correttamente, possono causare {\bf{memory leaks}} e {\bf{dangling pointers}}. \newline \newline ✔ `new` alloca memoria per name. \newline ✔ delete nel distruttore evita memory leaks.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Uso di std::unique\_ptr}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \#include \textless{}memory\textgreater{} // Per unique\_ptr \newline \newline class Person \{ \newline private: \newline std::unique\_ptr\textless{}std::string\textgreater{} name; \newline \newline public: \newline Person(const std::string\& n) : name(std::make\_unique\textless{}std::string\textgreater{}(n)) \{\} \newline \newline void display() const \{ \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} *name \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline Person p1("Alice"); \newline Person p2 = std::move(p1); // Usa il move constructor di unique\_ptr \newline \newline p2.display(); // Output: Name: Alice \newline // p1.display(); // ❌ Errore: p1 è stato svuotato \newline \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Con smart pointers, non dobbiamo gestire `new` e `delete` manualmente. \newline \newline ✔ Gestisce automaticamente la memoria (non serve delete). \newline ✔ Evita {\bf{shallow copy}}, perché `unique\_ptr` non è copiabile.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{`this` in Funzioni Membro Costanti}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{In una funzione membro dichiarata `const`, `this` diventa un puntatore a un oggetto costante (`const Person*`), quindi non si possono modificare i dati membri.% Row Count 4 (+ 4) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Esempio di Method Chaining con this}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{class Person \{ \newline private: \newline std::string name; \newline int age; \newline \newline public: \newline Person(std::string n, int a) : name(n), age(a) \{\} \newline \newline // Metodi che ritornano {\emph{this per concatenare chiamate \newline Person\& setName(std::string n) \{ \newline this-\textgreater{}name = n; \newline return }}this; \newline \} \newline \newline Person\& setAge(int a) \{ \newline this-\textgreater{}age = a; \newline return *this; \newline \} \newline \newline void display() const \{ \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} name \textless{}\textless{} ", Age: " \textless{}\textless{} age \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline Person p1("Alice", 25); \newline \newline // Method chaining grazie a 'this' \newline \seqsplit{p1.setName("Bob").setAge(30).display();} // Output: Name: Bob, Age: 30 \newline \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{`this` è spesso usato per ritornare l'oggetto corrente e permettere la chaining dei metodi.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Puntatore Implicito `this`}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Il puntatore `this` è un puntatore implicito che ogni oggetto di una classe possiede e che punta a se stesso. \newline % Row Count 3 (+ 3) ✔ È disponibile automaticamente in tutti i metodi non statici di una classe. \newline % Row Count 5 (+ 2) ✔ Contiene l'indirizzo dell'oggetto corrente. \newline % Row Count 6 (+ 1) ✔ Viene utilizzato per distinguere membri della classe da parametri con lo stesso nome e per ritornare l'oggetto corrente in metodi concatenati (method chaining).% Row Count 10 (+ 4) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Costruttori Sovraccaricati}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline private: \newline std::string name; \newline int age; \newline \newline public: \newline // 1️⃣ Costruttore predefinito \newline Person() : name("Unknown"), age(0) \{\} \newline \newline // 2️⃣ Costruttore con un parametro \newline Person(std::string n) : name(n), age(0) \{\} \newline \newline // 3️⃣ Costruttore con due parametri \newline Person(std::string n, int a) : name(n), age(a) \{\} \newline \newline // Metodo per mostrare i dati \newline void display() const \{ \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} name \textless{}\textless{} ", Age: " \textless{}\textless{} age \textless{}\textless{} std::endl; \newline \} \newline \};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Il {\bf{sovraccarico dei costruttori permette di definire più costruttori}} nella stessa classe, ognuno con parametri diversi. \newline \newline Se una classe non ha un costruttore definito esplicitamente, il compilatore genera automaticamente un {\bf{costruttore predefinito sintetizzato}}. \newline - Non prende parametri. \newline - Non inizializza esplicitamente i membri della classe (se non con valori predefiniti dei tipi). \newline - Viene creato automaticamente solo se non ci sono altri costruttori definiti.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Costruttore di Default Esplicito (= default)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{class Example \{ \newline public: \newline Example() = default; // Richiede al compilatore di generare il costruttore di default \newline \};} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Possiamo chiedere al compilatore di generare esplicitamente un {\bf{costruttore predefinito}} usando `= default` che funziona esattamente come il costruttore predefinito sintetizzato.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Uso di = delete}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{l'operatore `= delete` impedisce l'uso di funzioni o operatori specifici. \newline % Row Count 2 (+ 2) ✔ `= delete` impedisce l'uso di funzioni o operatori specifici. \newline % Row Count 4 (+ 2) ✔ Blocca la copia e l'assegnazione, utile per classi con gestione esclusiva delle risorse. \newline % Row Count 6 (+ 2) ✔ Evita conversioni implicite indesiderate. \newline % Row Count 7 (+ 1) ✔ Può impedire l'allocazione dinamica (`new`).% Row Count 8 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Copy \& Move Semantics}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \#include \textless{}cstring\textgreater{} // Per strcpy, strlen \newline \newline class Person \{ \newline private: \newline char{\emph{ name; \newline \newline public: \newline // 🏗 1️⃣ Costruttore normale \newline Person(const char}} n) \{ \newline name = new char{[}strlen(n) + 1{]}; \newline strcpy(name, n); \newline std::cout \textless{}\textless{} "Constructor called for " \textless{}\textless{} name \textless{}\textless{} std::endl; \newline \} \newline \newline // 📝 2️⃣ Costruttore di copia (Deep Copy) \newline Person(const Person\& other) \{ \newline name = new char{[}strlen(other.name) + 1{]}; // Nuova allocazione \newline strcpy(name, other.name); \newline std::cout \textless{}\textless{} "Copy constructor called for " \textless{}\textless{} name \textless{}\textless{} std::endl; \newline \} \newline \newline // 🔄 3️⃣ Operatore di assegnazione (Deep Copy) \newline Person\& operator=(const Person\& other) \{ \newline if (this != \&other) \{ // Evita auto-assegnazione \newline delete{[}{]} name; // Libera memoria esistente \newline name = new char{[}strlen(other.name) + 1{]}; \newline strcpy(name, other.name); \newline \} \newline std::cout \textless{}\textless{} "Copy assignment operator called for " \textless{}\textless{} name \textless{}\textless{} std::endl; \newline return {\emph{this; \newline \} \newline \newline // 🚀 4️⃣ Costruttore di spostamento (Move Constructor) \newline Person(Person\&\& other) noexcept \{ \newline name = other.name; // Prende il puntatore \newline other.name = nullptr; // Resetta il vecchio oggetto \newline std::cout \textless{}\textless{} "Move constructor called" \textless{}\textless{} std::endl; \newline \} \newline \newline // ➡️ 5️⃣ Operatore di assegnazione per spostamento (Move Assignment) \newline Person\& operator=(Person\&\& other) noexcept \{ \newline if (this != \&other) \{ \newline delete{[}{]} name; // Libera la memoria esistente \newline \newline name = other.name; // Prende la risorsa \newline other.name = nullptr; // Resetta l'oggetto originale \newline \} \newline std::cout \textless{}\textless{} "Move assignment operator called" \textless{}\textless{} std::endl; \newline return }}this; \newline \} \newline \newline // 🗑 Distruttore \newline \textasciitilde{}Person() \{ \newline delete{[}{]} name; \newline std::cout \textless{}\textless{} "Destructor called" \textless{}\textless{} std::endl; \newline \} \newline \newline void display() const \{ std::cout \textless{}\textless{} "Person: " \textless{}\textless{} (name ? name : "Empty") \textless{}\textless{} std::endl; \} \newline \}; \newline \newline int main() \{ \newline Person p1("Alice"); \newline Person p2 = p1; // Chiamata al costruttore di copia \newline Person p3("Bob"); \newline \newline p3 = p1; // Chiamata all'operatore di assegnazione \newline \newline Person p4 = std::move(p1); // Chiamata al costruttore di spostamento \newline p3 = std::move(p2); // Chiamata all'operatore di assegnazione per spostamento \newline \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{1️⃣ Costruttore di copia → Usato quando `p2 = p1`; per creare una copia separata. \newline 2️⃣ Operatore di assegnazione → Usato quando `p3 = p1`; per assegnare i dati. \newline 3️⃣ Costruttore di spostamento → Usato con `std::move(p1)`; per evitare la copia. \newline 4️⃣ Operatore di assegnazione per spostamento → Usato con `p3 = std::move(p2)`;. \newline 5️⃣ Distruttore → Libera la memoria quando gli oggetti escono dallo scope.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Getter \& Setter}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline private: \newline std::string name; \newline \newline public: \newline // Setter \newline void setName(std::string n) \{ name = n; \} \newline \newline // Getter \newline std::string getName() const \{ return name; \} \newline \}; \newline \newline int main() \{ \newline Person p; \newline p.setName("Alice"); \newline std::cout \textless{}\textless{} "Name: " \textless{}\textless{} p.getName() \textless{}\textless{} std::endl; // Output: Name: Alice \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{✔ Mantengono l'incapsulamento. \newline ✔ Possiamo validare i dati prima di modificarli.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Classi e Funzioni Amiche (`friend`)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline private: \newline std::string name; \newline \newline public: \newline Person(std::string n) : name(n) \{\} \newline \newline // Dichiarazione della funzione amica \newline friend void showPerson(const Person\& p); \newline \}; \newline \newline // Definizione della funzione amica \newline void showPerson(const Person\& p) \{ \newline std::cout \textless{}\textless{} "Friend Function - Name: " \textless{}\textless{} p.name \textless{}\textless{} std::endl; \newline \} \newline \newline int main() \{ \newline Person p("Bob"); \newline showPerson(p); // Output: Friend Function - Name: Bob \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Le classi amiche e funzioni amiche possono accedere ai membri privati di una classe senza bisogno di getter/setter. \newline \newline ✔ Una funzione amica {\bf{non è un membro della classe}}, ma può accedere ai suoi dati privati. \newline ✔ Può essere una funzione normale o un metodo di un'altra classe.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.232 cm} x{1.656 cm} x{1.728 cm} x{1.584 cm} } \SetRowColor{DarkBackground} \mymulticolumn{4}{x{8.4cm}}{\bf\textcolor{white}{Ereditarietà}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Tipo di Ereditarietà}} & {\bf{Membri public}} & {\bf{Membri protected}} & {\bf{Membri private}} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} public & \seqsplit{Rimangono} public & \seqsplit{Rimangono} \seqsplit{protected} & Non \seqsplit{accessibili} \tn % Row Count 6 (+ 3) % Row 2 \SetRowColor{LightBackground} protected & \seqsplit{Diventano} \seqsplit{protected} & \seqsplit{Rimangono} \seqsplit{protected} & Non \seqsplit{accessibili} \tn % Row Count 9 (+ 3) % Row 3 \SetRowColor{white} private & \seqsplit{Diventano} private & \seqsplit{Diventano} private & Non \seqsplit{accessibili} \tn % Row Count 11 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}----} \SetRowColor{LightBackground} \mymulticolumn{4}{x{8.4cm}}{L'ereditarietà permette di creare una nuova classe (`classe derivata`) basata su un'altra (`classe base`).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}----} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Esempio: Ereditarietà public cpp Copia Modifica}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline protected: // Accessibile dalle classi derivate \newline std::string name; \newline \newline public: \newline Person(std::string n) : name(n) \{\} \newline \newline void display() const \{ std::cout \textless{}\textless{} "Name: " \textless{}\textless{} name \textless{}\textless{} std::endl; \} \newline \}; \newline \newline // Classe derivata \newline class Student : public Person \{ \newline private: \newline int studentID; \newline \newline public: \newline Student(std::string n, int id) : Person(n), studentID(id) \{\} \newline \newline void show() const \{ \newline display(); // Chiamata al metodo della classe base \newline std::cout \textless{}\textless{} "Student ID: " \textless{}\textless{} studentID \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline Student s("Alice", 1234); \newline s.show(); \newline // Output: \newline // Name: Alice \newline // Student ID: 1234 \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{✔ Student eredita Person con ereditarietà public, quindi display() è accessibile. \newline ✔ name è protected, quindi accessibile nella classe derivata.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Esempio: Ereditarietà private cpp Copia Modifica}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{class Employee : private Person \{ \newline private: \newline int employeeID; \newline \newline public: \newline Employee(std::string n, int id) : Person(n), employeeID(id) \{\} \newline \newline void show() const \{ \newline display(); // Possibile perché ereditiamo `private` (membri public diventano private) \newline std::cout \textless{}\textless{} "Employee ID: " \textless{}\textless{} employeeID \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline Employee e("Bob", 5678); \newline e.show(); \newline \newline // e.display(); ❌ ERRORE! (diventa private in Employee) \newline \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{✔ Con private, i membri `public` della classe base diventano privati in `Employee`. \newline ✔ `display()` può essere usato solo dentro `Employee`, ma non dall'esterno.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Ereditarietà Multilivello}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Person \{ \newline protected: \newline std::string name; \newline public: \newline Person(std::string n) : name(n) \{\} \newline void display() const \{ std::cout \textless{}\textless{} "Name: " \textless{}\textless{} name \textless{}\textless{} std::endl; \} \newline \}; \newline \newline // Student eredita da Person \newline class Student : public Person \{ \newline protected: \newline int studentID; \newline public: \newline Student(std::string n, int id) : Person(n), studentID(id) \{\} \newline \}; \newline \newline // GraduateStudent eredita da Student \newline class GraduateStudent : public Student \{ \newline private: \newline std::string thesisTitle; \newline public: \newline \seqsplit{GraduateStudent(std::string} n, int id, std::string thesis) \newline : Student(n, id), thesisTitle(thesis) \{\} \newline \newline void show() const \{ \newline display(); // Da Person \newline std::cout \textless{}\textless{} "Student ID: " \textless{}\textless{} studentID \textless{}\textless{} std::endl; \newline std::cout \textless{}\textless{} "Thesis: " \textless{}\textless{} thesisTitle \textless{}\textless{} std::endl; \newline \} \newline \}; \newline \newline int main() \{ \newline GraduateStudent g("Bob", 5678, "AI Research"); \newline g.show(); \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Una classe può ereditare da una derivata, propagando i membri lungo la gerarchia. \newline \newline ✔ `GraduateStudent` eredita da `Student`, che eredita da `Person`. \newline ✔ `display()` è chiamato da `GraduateStudent`, anche se appartiene a Person`. \newline ✔ `studentID` è protetto, quindi accessibile da `GraduateStudent`, ma non da `main()`.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Ereditarietà Multipla}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\#include \textless{}iostream\textgreater{} \newline \newline class Athlete \{ \newline protected: \newline std::string sport; \newline public: \newline Athlete(std::string s) : sport(s) \{\} \newline void showSport() const \{ std::cout \textless{}\textless{} "Sport: " \textless{}\textless{} sport \textless{}\textless{} std::endl; \} \newline \}; \newline \newline class Student \{ \newline protected: \newline int studentID; \newline public: \newline Student(int id) : studentID(id) \{\} \newline void showID() const \{ std::cout \textless{}\textless{} "Student ID: " \textless{}\textless{} studentID \textless{}\textless{} std::endl; \} \newline \}; \newline \newline // Classe che eredita sia da Athlete che da Student \newline class StudentAthlete : public Athlete, public Student \{ \newline public: \newline \seqsplit{StudentAthlete(std::string} s, int id) : Athlete(s), Student(id) \{\} \newline \newline void show() const \{ \newline showSport(); \newline showID(); \newline \} \newline \}; \newline \newline int main() \{ \newline StudentAthlete sa("Basketball", 2023); \newline sa.show(); \newline return 0; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{✔ `StudentAthlete` eredita sia da `Athlete` che da `Student`. \newline ✔ Può chiamare i metodi di entrambe le classi (`showSport()` e `showID()`).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}