$ % & # _ { } \verb=\ ~ ^= are special characters and has special meaning to latex. You can use a leading \textbackslash\ to use them. To print $, write \textbackslash$
\subsection{Latex commands}
Each latex command starts with a \textbackslash and contains only letters. Example: \verb=\maketitle=, \verb=\tableofcontents= etc.\ Parameters to a command are specified inside {} and optional parameters are specified inside [ ]. For example \verb=\documentclass[10pt]{article}=.
\section{Writing}
\subsection{Modes in \LaTeX}
\begin{description} \item[Paragraph mode] Normal mode \item[Math Mode] For mathematical equation. Text inside \verb=(…)= or \verb=$…$= or \verb=$$…$$= or \verb=\begin{equation}…\end{equation}= or \verb=\begin{displaymath}…\end{displaymath}= \item[Left to right mode] Text are displayed from left to right without line breaks. text inside \verb=\mbox{}= \end{description}
\subsection{Creating a New Paragraph}
A blank line creates a new paragraph.
\subsection{Spaces}
\subsubsection{Inserting Spaces}
\verb=,= is used for inserting a space.
\subsubsection{Space after a period}
Latex assumes end of sentence if it found period after small case later. In that case it puts extra space after period. But for the cases like ``etc.’’ a space followed by \verb== should be used after period like \verb=etc.\ =. A space followed by \verb== means inter word space.
If ending of a sentence contains a uppercase letter to end the sentence use \verb=@= before period.
\subsubsection{Space after a latex command}
All spaces are ignored after a latext command like \verb=\LaTeX= command. To make a space after \LaTeX\ a space followed by \verb== should be used like \verb=\LaTeX\ =. Another way to do this is to use empty {} after a command like \verb=\LaTeX{}=.
\subsection{Dashes}
\begin{itemize} \item\verb=-= A intra-word dash or hyphene. Example: X-ray. \item\verb=–= A number range dash. Example: 1–10 \item\verb=—= A punctuation dash. Example: — \end{itemize}
\subsection{Quotations}
\verb== is used for single quotation start ().\ \verb=’= is used for single quotation end (‘).\ \verb== is used for double quotation start ().\ \verb=”= is used for double quotation end (“).
\subsubsection{Putting Quotation in a Quotation}
\verb=\,`Ah!`\, She said= produces ``,,`Ah!’,,‘’ She said
\subsection{Commenting}
\verb=%= is used for commenting. Latex ignore all character after \verb=%= to the end of the line. Also ignores space in the beginig of the next line.
\section{\LaTeX Commands List}
\begin{itemize} \item\verb=\documentclass[]{}= — To specify document type. Arguments can be book, article, report etc. Options\footnote{Options are specified inside the square brackets} are:
\begin{enumerate}
\item 11pt --- 10\% larger than 10pt.
\item 12pt --- 20\% larger than 10pt.
\item twoside --- to print in both sides.
\item twocolumn --- two column in a single page.
\end{enumerate}
\item\verb=\usepackage{}= --- To use external packages.
\item\verb=\title{}= --- To specify document title.
\item\verb=\author{}= --- To specify documnet author. Multiple authors cab be specified using \verb=\and= command.
\item\verb=\begin{}= --- To begin any block. like \verb=\begin{document}= to begin any document, \verb=\begin{quote}= begins a long quotation, \verb=\begin{math}=begins a math block etc.
\item\verb=\end{}= --- ends any block that begins with \verb=\begin{}=
\item Argument of \verb=\begin= and \verb=\end= are called environments. They create different display environments. Every declaration or command can be environment like \verb=\emph= can also be written as environment like \verb=\begin{emph}= ... \verb=\end{emph}= Here is a list of different environments:
\begin{description}
\item[document] Document environment.
\item[quote] Shor quotation environment.
\item[quotation] Long quotation environment.
\item[itemize] Unordered list environment.
\item[enumerate] Ordered list environment.
\item[description] Description list environment like this one.
\item[displaymath] Display math equations in separate line but without equation number.
\item[equation] Displayequation in separate line with equation number for further referance.
\end{description}
\item\verb=\maketitle= --- To create title. It must be inside \verb=\begin{document}=.
\item\verb=\part= --- Create parts of a document. Doesn't effect documnet numbering.
\item\verb=\chapter= ---- Create chapters. No applicable for article document class.
\item\verb=\section= --- Specify a section.
\item\verb=\subsection= --- Specify a sub-section of a section.
\item\verb=\subsubsection= --- Specify a sub-section of a sub-section.
\item\verb=\appendix= --- Specify an appendix.
\item\verb={}= --- Curly braces can be used for defining scope. Example --- Input: \verb=Hello, {\em aagontuk}= Output: Hello, {\em aagontuk}
\item\verb=\today= --- Current date \today
\item\verb=\TeX= --- Shows \TeX
\item\verb=\LaTeX= --- Shows \LaTeX
\item\verb=\ldots= --- Produces \ldots
\item\verb=\emph{}= --- To emphasize text. Example: I will \emph{emphasize} it.
\item\verb=\mbox{TEXT}= --- Never breaks TEXT.\
\item\verb=\footnote{footnote}= --- To create a footnote. Example: Footnote\footnote{Please find the foornote here}
\item\verb=\\= --- New line.
\item\verb=\\*= --- New line but prevents a new page.
\item\verb=\newline= --- New line.
\item\verb=\hfill \break= --- New line.
\item\verb=\newpage= --- New Page.
\item\verb=\hspace{xmm}= --- x mm horizontal space.
\item\verb=\vspace{xmm}= --- x mm vertical space.
\end{itemize}
\section{Useful Tricks}
\subsection{Centered section header without number}
In latex usually section are left aligned and numbered. If a starred version of the section command is used it doesn’t generate number. To make the section header center aligned `sectsty’ package can be used.
<!-- Define description of a web page --> <metaname="description"content="This page is about html cheatsheet">
<!--To state author of the page> <meta name="author" content="Aagontuk"> <!-- To set character encoding --> <metacharset="UTF-8">
<!-- To refresh page in every 15 sec --> <metahttp-equiv="refresh"content="15">
<!-- To make the page look good in every device --> <metaname="viewport"content="width=device-width, initial-scale="1.0"">
<body>
Attributes:
alink="color" - color of a link when it is clicked.
link="color" - color of unvisited link.
vlink="color" - color of visited link.
background="image.png" - background image of a page if bgcolor not set.
bgcolor="color" - background color of a page if background image not set.
text="color" - color of the texts in the page.
<h1> to <h6>
Creates headlines in html document.
<hr>
Creates a horizontal line. Used for styling the document.
Attributes:
align - Specifies alignment.
size="pixel" - Specifies height in pixel. Eg. size=”10”
width="x%" - Specifies width in %. Eg. width=”50%”
noshed - Line will be of a solid color.
<p>
Creates a paragraph. Omit any line breaks(extra space, tab etc).
<pre>
Use fixed width font. Preserve line breaks.
Formatting Tags
<b> - Bold Text.
<i> - Italic Text.
<u> - Underline.
<strong> - Strong Text.
<em> - Emphasized Text.
<small> - Samll Text.
<sup> - Superscript.
<sub> - Subscript.
<mark> - Marked Text. Text with some background color.
<del> - Deleted Text. Striked.
<ins> - Inserted Text. Underlined.
Quotations
Quoting with quotation mark
Texts under <q> tag are placed under quotation mark.
Quoting using <blockquote>
<blockquote> is used to quote text from another source. Text under <blockquote> are indented.
1 2 3 4 5 6 7
<p>Here is some information about Themis:</p> <blockquotecite="https://en.wikipedia.org/wiki/Themis"> Themis is an ancient Greek Titaness. She is described as "[the Lady] of good counsel", and is the personification of divine order, fairness, law, natural law and custom. Her symbols are the Scales of Justice, tools used to remain balanced and pragmatic. </blockquote>
<abbr> for Abbreviation
<abbr> is used for abbreviation. Show full form under cursor.
1 2 3
<p> Richard M. Stallman is the creator of the <abbrtitle="GNU is not Unix">GNU</abbr> system. </p>
<address> for Contact Information
1 2 3 4
<address> Luke Skywalker</br> Naboo System</br> </address>
<cite>
<cite> is used for mentioning the title of someone’s work.
1
<p><cite>Star Wars</cite> directed by George Lucas</p>
<html> <head> <title>Internal CSS</title> <style> h3 { font-size: 30px; font-family: garamond; } p.redText { color: red; font-size: 14px; } p.greenText { color: green; font-size: 20px; } </style> </head> <body> <h3> Internal CSS Example using class </h3> <pclass="redText"> This text should be red </p> <pclass="greenText"> This text should be green </p> </body> </html>
Extarnal CSS
Separate CSS file is used. <link> tag is used to use the file in the document.
<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <body> <h2class="header"> Create an Account in Hell NOW! </h2>
<formaction="process.php"method="post"autocomplete="on"> <fieldset> <legend>Basic Information</legend> Your Name: <inputtype="text"name="name"value="name"placeholder="Name"size="40"autofocus="on"/><br/> Your Gender:<br/> <inputtype="radio"name="gender"value="male"/>Male<br/> <inputtype="radio"name="gender"value="female"/>Female<br/> <inputtype="radio"name="gender"value="other"checked="checked"/>Other<br/> Married?<br/> <inputtype="checkbox"name="married"value="no"checked="checked"/>No<br/> <inputtype="checkbox"name="married"value="yes"/>Yes</br> </fieldset>
<fieldset> <legend>Insanity Check</legend> Pick <spanclass="color">Red</span> color: <inputtype="color"name="color"value="blue"><br/> What is the value of Π: <inputtype="number"name="pi"value="3"min="1"max="9"step="2"/><br/> Can you slide for no reason? <inputtype="range"name="slide"value="50"min="0"max="100"step="2"/> </fieldset>
<fieldset> <legend>Create Username</legend> Username: <inputtype="text"name="uname"placeholder="username"pattern="[A-Za-z]{6}"label="Only letters and upto six characters"required/><br/> Password: <inputtype="password"name="pass"pattern="[A-Za-z0-9]{6}"label="Only letters and numbers upto 6 characters"required/><br/> Upload Image:<br/> <inputtype="file"name="image"/> </fieldset>
git config is used to create and modify system/user/repo git configuration file.
Options:
–system - will set the config system wide. for all user’s all repos in the system. System wide git config file is stored generally in /etc/gitconfig
–global - will set the config user wide. For a specific user’s all git repos. stored in ~/.config/git/config or user’s home directory.
–local - will set the config for a specific repo. Stored in .git/config
–list - Show all the list of current config variables and their values.
Examples:
1 2 3 4
git config --global user.name 'aagontuk' git config --global user.email 'aagontuk@mail.com' git config --global core.editor vim git config user.name # will show value of user.name
Initializing a project
git init is used to initialize a project as git repository.
1
git init
Cloning a repository from remote
git clone is used for cloning a remote repository into local system.
git status is used to see status of the project files. Untracked/tracked/modified/staged.
1 2
git status # Show details status git status -s # Show brief status
Adding files to staging area
git add is used to add untracked/modified files to staging area and prepare for commit. If a directory is added, its contents will be added recursively.
Adding whole file:
1
git add README.md
Adding portion of a file:
1
git add -p README.md # This will bring an interactive prompt
Inspect changes of a file
git diff is used to show changes of a file
1 2 3
git diff # Shows changes between last staged and unstaged git diff --staged # Shows changes between the last commit and staged git diff COMMIT_HASH~ COMMIT_HASH # Show diff between last commit and its ancestor
Creating and applying patch file
For creating patch file use git diff:
1
git diff > mypatch.patch
If you want add untracked files too first stage them using git add then create the patch file:
git commit is used for commiting changes that are staged
1 2 3 4
git commit # To commit changes that are staged. git commit -m "COMMIT_MSG" # Commit with inline commit message. git commit -a # stage all tracked modified files and commit. git commit -v # will add diff of changes in the commit message.
Removing files
git rm is used to remove files.
Following command will remove a file from tracking and also remove from system(HDD).
1
git rm project_file
If the file is already modified or staged, then to remove -f have to be used.
1
git rm -f project_file
To remove only from git but not from the system(HDD). So that git no longer track the file.
1
git rm --cached project_file
Moving/Renaming files
git mv is used to rename files/folders
1
git mv project_file my_project_file
View logs
git log is used to view commit logs/history
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
git log # Show entire commit log of the repo git log -n # Show last n commit logs git log -p -n # Show last n commit log including change/patch/diff in those commits git log --stat # Commit log witch list of modified files and stat of the changes in those files git log --pretty=oneline # show each commit log in one line with only full SHA and subject git log --pretty=short # Log with SHA, author and subject git log --pretty=full # Log with SHA, author, commiter, subject, message body git log --pretty=fuller # Log with SHA, author, commiter, subject, message body, write and commit dates git log --oneline # Show first 7 characters of SHA value, Heading git log --format="%h - %an, %ad: %s" # Custom log output format git log --graph # Will show a ascii graph of commit history git log --relative-date # Will show relative date(days, weeks etc) rather than exact date git log --since=2.weeks # Show all commits since a specific date or relative date git log --until=2.weeks # Show all commit before a specific date or relative date git log --author=AUTHOR # Show the logs of a specific author git log --follow -- FILE # Show all the commits to a specific file git log testing # Show the logs of testing branch git log --all # Show logs of all branches. By default shows only the logs of checked out branch
Modifying last commit
After a commit, to redo that commit for additional changes git commit --amend can be used. This is useful when accidentally forgot to add files to a commit.
1 2 3
git commit -m "Serious bugfix" # Accidentally commited without forgotten_files git add forgotten_files # forgotten_files is added git commit --amend # Previous commit will be modified by adding forgotten_files
If this command is used just after a commit, editor will show up to edit the commit message. So this can be used to modify minor changes in the latest commit message.
After files are staged in the staging are using git add command, to remove the file from the staging area:
1
git reset HEAD file_name
Unmodifying a modified file
When a file is modified which is tracked by git, git show the modified flag in git status. Following command can be used to discard the modification. If this is used, git will no longer show it as modified, also modifications to that file will be gone.
This will only change the local branch name. To change the remote branch name too you have do first push the renamed branch to remote:
1
git push --set-upstream origin good_branch_name
Now there will be two branch in remote remotes/origin/bad_branch_name and remotes/origin/good_branch_name. Remove remote/origin/bad_branch_name
1
git push origin --delete bad_branch_name
Merging a branch to another branch
Let’s say your are now in testing branch. You have added some changes and now want to merge the commits of testing branch into master branch:
1 2
git checkout master git merge testing
Remote Branches
Remote branches are named like <remote_name>/<remote_branch_name>. For example origin/master. This points to the latest commit of your remote repository at the time of your last synchronization.
Fetching commits from remote repository
1
git fetch <remote_name>/<remote_branch_name>
This will synchronize the remote branch with the local repository. For example if your remote branch name is origin/master this will synchronize orgin/master with the local repository. Note that this will not merge commits from remote branch(origin/master) into your local branch(master). You have to do it manually.
Pushing/fetching a new branch to/from remote repository
For example you have created a new branch named testing and added some commits to it. Now you want to upload it to your remote repository:
1
git push origin testing
This will create a new branch named testing in your remote repository. If you want to name the remote branch name different from the local branch name:
1
git push origin testing:experimental
For the next example lets say you didn’t name the differently. Now if someone who is also forked that remote repository do fetch, a new remote branch named origin/testing will be created in their local repository. Not this will not create any new local branch to work on for them. They will have to do it manually:
1
git checkout -b testing origin/testing
You can also use this shortcut if you keep the local branch name and remote branch name same:
1
git checkout testing
If you want to give a different name to the local branch:
1
git checkout -b experimental origin/testing
Tracking Branch
Checking out a local branch from a remote branch creates a tracking branch. Tracking branch means that local branch and the remote branch has a direct relationship with each other. If you are in that local branch when you do a push git will automatically push the commits to the remote branch and when you do pull git will automatically merge all the commits from the remote branch to that local branch.
For example in above example if your are in testing branch, when you do a pull git will merge all the commits from origin/testing to testing automatically. And after working on testing when you do push git will automatically push all the commits to origin/testing.
If you have a local branch which don’t have a tracking branch or you want to change the remote tracking branch. For example if you currently on testing branch and want to set origin/testing as you remote tracking branch:
1
git branch -u origin/testing
Pulling
For automatically fetching commits from remote branch and merging with local tracking branch use:
1
git pull
It is equivalent to:
1 2
git fetch git merge
Deleting a remote branch
1
git push origin --delete testing
This will delete branch testing from remote repository.
Cherry Picking
For merging a specific commit or set of commits from a brach to another branch.
In below example COMMIT_HASH is the hash of the commit you want to cherry pick from another branch:
For cherry picking a set of commits(A, B are commit hash):
1 2
git checkout stable-branch git cherry-pick A^..D
This assumes A is older commit than D and will include commit hash A, B, C, D:
1 2
git checkout stable-branch git cherry-pick A..D
If you want to exclude A:
Rewriting history
Removing commits
Lets say your commit history looks like this:
Number (newest-oldest)
Commit Hash
Commit Message
1
4d884d0
Important fix
2
5540e24
server fix
3
4c5199f
client fix
4
7879940
My awesome fix
5
2c27f34
minor fix
If you want to remove consecutive commits you can use git rebase. For example if you want to remove commit 3 and 4 you can do following:
1
git rebase --onto <branch_name>~<number of the oldest commit you want to remove> <branch_name>~<number of the oldest commit you want to keep> <branch_name>
So if you want to remove 3 and 4 in master branch:
1
git rebase --onto master~4 master~2 master
Now if you want to remove non-consecutive commits, you can use git cherry-pick. For example if you want to remove commit 2 and 4 you have to do following procedure:
Go to oldest usable commit(In this case 5)
Create a new branch
cherry pick the commits you want to keep(In this case 3 and 1) after that commit(In this case 5).
Checkout to the previous branch you were in.
Do a hard reset to the last usable commit(In this case 5)
Merge the new branch in this branch
So lets say in our case you were in master branch and want to remove commit 2 and 4:
Version Control System: Version control is a system that records changes to a file or set of files over time. Each change of those files can be tracked easily. So its is possible to revert back to a previous version etc.
Git: Git is a command line program for distributed version controlling
GitHub: GitHub is a web-based Git repository hosting service. It offers all the distributed version control and software management functionality of Git. It makes it easy to save project remotely, version controlling, collaborate with multiple developers on a project etc.
Configuring Git
Configure Name & Email: First we have to add name and email. If no name or email is added pc’s username will be used as username and host name will be used as email. This username and email is for your local repository and have no relation with remote repository’s(like github) username and email.
Configure color: Configure git so that terminal output becomes color coded.
git config --global color.ui 'auto'
Creating & Publishing Repository
Creating Local Repository
Creating repository: To make a local repository first create a folder where all other files & folder of this project will be saved. I am creating a project called cheatsheets where I will store all my cheatsheets. So first I will create a directory named cheatsheets.
me@my-pc:~$ mkdir cheatsheets
initializing: Now I have to go to in my newly created directory & do git init command to initialize git. This will create a hidden folder .git, where git will store all its information about this project for tracking.
1 2
me@my-pc:~$ cd cheatsheets me@my-pc:~/cheatsheets$ git init
Now I will add files of my project to this directory. Lets say I have created a file called git_and_github.md which is my cheatsheet about git & github.
me@my-pc:~/cheatsheets$ ls git_and_github.md
Checking status:git status command gives the current status of the local repository.
me@my-pc:~/cheatsheets$ git status
1 2 3 4 5 6 7 8 9 10
On branch master
Initial commit
Untracked files: (use "git add <file>..." to include in what will be committed)
git_and_github.md
nothing added to commit but untracked files present (use "git add" to track)
Add to staging area: So its saying there is an untracked file. After adding contents to my files I have to add the files to staging area using git add command, So that git can track those files & their contents. Now I am adding git_and_github.md file to staging area.
me@my-pc:~/cheatsheets$ git add git_and_github.md
Now git status gives:
me@my-pc:~/cheatsheets$ git status
1 2 3 4 5 6 7 8
On branch master
Initial commit
Changes to be committed: (use "git rm --cached <file>..." to unstage)
new file: git_and_github.md
Commiting: To add the files into main repository we have to use git commit command. A commit message with -m option will have to add with this. Now each time we change project’s files we have to use this command to add those changes into main repository. Commit message can be anything you want. Usually it is used for specifying what has been added or changed in a specific version of a file. It will also your github commit message when we will upload our local repository to remote github repository.
Updating changes: After modifying a file, changes will have to send into staging area issuing git add again. And commit changes to repository using git commit. Adding & commiting can be done in a single command issuing git commit -a.
me@my-pc:~/cheatsheets$ git commit -a -m "updated content"
Now I will publish my local repository to a remote repository like GitHub.
Setup GitHub: Create GitHub accout. Set up ssh (optional) etc.
Creating a remote repository: Now I have to create a repository in GitHub which will be the remote repository for my local repository. My local repository will be synced in this remote repository. Repositories can be public or private.
I am creating a repository named cheatsheets in GitHub. The repository URL of github are in this form github.com/USERNAME/REPOSITORYNAME.git. So my newly created repository’s URL will be: https://github.com/rashfaqur/cheatsheets.git. For SSH it will be git@github:USERNAME/REPOSITORYNAME.git. In my case it is git@github.com:rashfaqur/cheatsheets.git
Note: If you want to use SSH you have to use SSH type URL for SSH to work.
Adding remote repository into local repository: Now I have to add my remote repository URL / address using git remote add URL_ALIAS URL command, so that my local repository can know my remote repository. Were URL is my remote repository’s URL and URL_ALIAS is a sudo name for remote repository URL so that I don’t have to type URL in future. URL_ALIAS can be any name. Commonly origin is used. I am using origin & SSH URL.
Pushing local repository:git push -u URL_ALIAS BRANCH_NAME command is used to push / publish local repository into remote Repositorie. Where BRANCH_NAME is the branch name. Main branch is called master. There can be several branch. I will add my porject into master branch.
me@my-pc:~/cheatsheets$ git push -u origin master
1 2 3 4 5 6 7 8
Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 1.24 KiB | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To git@github.com:rashfaqur/cheatsheets.git * [new branch] master -> master Branch master set up to track remote branch master from origin.
Next time after commiting changes I can only issue git push to push all the changes into remote repository.
If uniform initialization is used with no value. Default is 0.
1
int numRings{}
Integers
Fixed width integers
Will give fixed sized integer in all architecture.
1 2 3 4 5 6 7 8 9 10 11 12
#include<cstdint>// for fixed width integers
/* * 8 bit singed integer. Many systems consider them as chars. So it is better * to not use them if using integers is the purpose */ int8_t var;
uint8_t var; // 8 bit unsigned integer
intN_t var; // N = 16, 32, 64 bits signed integer uintN_t var; // N = 16, 32, 64 bits unsigned integer
Fixed width integers performance is machine dependent. To get the fastest integer type on a specific machine use int_fastN_t. It will give the fastest integer which is at least N bits long. N = 8, 16, 32, 64.
1
int_fast32_t var;
To get the smallest integer which is at least N bits long use int_leastN_t where N = 8, 16, 32, 64.
1
int_least64_t var;
Floating point numbers
Setting precision of a floating point number:
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream> #include<iomanip>// for std::setprecision()
intinteger(50); // integer floatf(0.05f); // used f suffix as default literal is double type doubled(0.31416); // double floating literal inthex(0xa0); // hexadecimal literal intoct(012); // Octal literal intbin(0b1010); // Binary literal
intlongNumber(1'23'570)// c++14 only
Constants
1 2 3 4 5 6 7 8 9
constdoubleavg(6.023e23); constdouble massEarth; // This is not allowed
intx(50); constinty(x)// This is allowed constexprdoubleadg(9.8); // Compile time constant. Value of the constant // must be resolved in compile time otherwise // will generate an error. This is c++11 feature
Variable Scopes and duration
shadowing:
1 2 3 4 5 6 7 8 9 10 11 12
intnumber(5);
if(number == 5){ int number; // local variable
number = 10; // will effect only local variable // this is shadowing
std::cout << number << std::endl; // will print local }
std::cout << number << std::endl; // will print outer block number
Global scope operator
:: is the global scope operator.
1 2 3 4 5 6 7 8
intx(50); // global variable
intmain(){ intx(40);
std::cout << x << std::endl; // will print local x std::cout << ::x << std::endl; // will print global x }
Internal Variable: Can be used anywhere in the file they are defined but not out of the file.
External Variable: Cab be used across multiple files. Global variables are by default external. static keyword can be used to make them internal.
Console Input/Output
Console I/O Methods
std::cin is used for console input. std::cin takes inputs untill first whitespace.
std::getline() is used to take whole line as input.
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream> #include<string>
intmain(){ std::string name;
std::cout << "Enter Name: "; std::getline(std::cin, name); std::cout << "Your name is: " << name;
return0; }
Error Handling in Console Input
std::cin takes upto newline from the input stream. So it will be a problem if any other input function is used after taking numeric input from std::cin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream> #include<string>
intmain(){ std::string name; int select;
std::cout << "Select: "; std::cin >> select;
std::cout << "Enter name: "; std::getline(std::cin, name); // will not work std::cout << "Your name is: " << name << "! You have selected: " << select;
return0; }
To solve this problem std::cin.ignore(n, ch) can be used where n is the number of character to ignore from the input stream before ch character is found.
/* * Input will fail if a valid number isn't typed. * if input fails, cin will set fail flag and stop extracting * characters from input stream. */ if(std::cin.fail()){ std::cout << "Please enter a floating number" << std::endl; std::cin.clear(); /* Clear fail flag */ std::cin.ignore(32767, '\n'); /* Clear input stream */ } else{ return d; } } }
std::cout << "There are " << inStore[Store::LM7805] \ << " LM7805 in store" << std::endl;
return 0; }
Relation Between Array and Pointer
Arrays are actually pointers. It points to the first element of the array.
1 2 3 4 5 6 7 8 9 10 11
#include<iostream>
intmain(){ int arr[2] = {1, 2};
/* Following two address will be same*/ std::cout << arr << std::endl; std::cout << &arr[0] << std::endl;
return0; }
Difference Between Array and Pointer to Array
The type of the array is int (*)[n] if it is an integer array but the type of the pointer to that array is int *. Array type contains the size information of the array. When array is dereferenced or assigned to a pointer it implicitly converts itself into type * from type (*)[n] so size information is lost. Here is an example of this behaviour:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<iostream>
intmain(){ int arr[5] = {1, 2, 3, 4, 5}; int *arrPtr = arr; // arr is converted from int (*)[2] to int *
/* Will print the size of the array which is 5 * 8 bytes */ std::cout << sizeof(arr) << std::endl;
/* Will print the size of the pointer which is 8 bytes */ std::cout << sizeof(arrPtr) << std::endl;
return0; }
String Constants Using Fixed Sized Array and Pointer
intmain(){ /* * keep the string constant in memory with r/w access * and return the pointer to it. * So string constant can be changed any time later */ char arr[] = "hello, world";
/* * Keep the string constant in read-only section of memory * so it can't be changed */ char *text = "GNU is not Unix";
/* As it is a constant so its better to initialize following way */ constchar *text = "GNU is not Unix";
arr[0] = 'g'; // This OK
/* * In this case as string constant is kept in read-only * memory, doing this will generate segmentation * fault */ *(text + 2) = 'O';
std::cout << arr << std::endl; std::cout << text << std::endl;
return0; }
Pointers
Definig NULL Pointer C++ Way
From C++11 nullptr keyword can be used to define a NULL pointer.
char ch = 'P'; // pointing to a char ptr = &ch; std::cout << static_cast<char*>(ptr) << std::endl;
return0; }
Converting A Pointer Address to Integer
Using reinterpret_cast<>:
1 2 3 4 5 6 7 8 9 10
#include<iostream>
intmain(){ int x = 17; unsignedint addressX = reinterpret_cast<int>(&x);
std::cout << addressX << std::endl;
return0; }
Dynamic Memory Allocation
There are three basic type of memory allocation:
Static memory allocation: Static and global variables. Allocated when program runs. Persist throught the program life. Memory is taken from the stack.
Atomatic memory allocation: Function parameter and local variables. Allocated when enter into relevent block and deallocated when exited the block. Memory is taken from the stack.
Dynamic memory allocation: Memory allocated and deallocated dynamically. Memory is taken from the heap.
Allocating Memory dynamically
Dynamically memory is allocated using the new keyword.
1 2 3 4 5 6 7 8 9
#include<iostream>
intmain(){ int *ptr = newint; // dynamically an integer is allocated.
*ptr = 5;
return0; }
Deallocating memory
Memory is deallocated using the delete keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream>
intmain(){ int *ptr = newint(5); // memory is allocated to the pointer
/* memory is deallocated. * memory is realesed by os. */
delete ptr;
/* still the pointer is holding the memory address * so its better to make it null */ ptr = 0; ptr = nullptr; // c++11
return0; }
Memory leak
memory leak happens when allocated memory can’t be deallocated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
voiddoSomthing(){
/* Memory is allocated but not deallocated * so memory leak happens when the variable * goes out of scope as there is no way * to deallocate in that case */
int *ptr = newint; }
intmain(){ doSomthing(); return0; }
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
intmain(){ int *ptr = intnew;
int val;
// assigning to a address with out deallocating ptr = &val; // memory leak
return0; }
1 2 3 4 5 6 7 8 9 10
#include<iostream>
intmain(){ int *ptr = newint(5);
// allocating new memory without deallocating previous one int *ptr = newint(10);
return0; }
Reference Variables
Create alias for a variable. Basically share same memory address. Must be initialized with an addressable object. Can be used in function to pass parameter by reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
intmain(){ intx(10); int &y = x; // reference variable
/* * will output: * 10 * 10 */ std::cout << x << std::endl std::cout << y << std::endl
return0; }
For Each Loop
Only works from c++11 above
Can’t be used in case of decayed arrays and dynamically allocated arrays.
/* lambda function example: used to make ~bitvect */ std::transform(bitvect.begin(), bitvect.end(), bitvect.begin(), [](bool b){ return b == 1 ? 0 : 1; }); return0; }
Syntaxt:
[&](){}: Capture all outside variable by reference. [=](){}: Capture all outside variable by value. [&x](){}: Capture only outside variable x by reference. [x](){}: Capture only outside variable x by value. [&, x](){}: Capture all outside variable by reference but x by value. []() -> Type {}: To specify return type.
/* Have to initialize first otherwise linker error will generate */ int ID::m_id = 1;
intmain(){ std::cout << ID::getID << std::endl;
return0; }
Member Types
In C++ classes can have memeber types or nested types. They make the class easy to maintain. For example in the following example it will be easy to change the type from int to double. It need to change in only one line.
C++ structs and classes are same. Only difference is that all members in structs are public.
Friend function and friend class
Friend functions and classes can access the private members of a class. In the following example printWeather() is friend of both Humidity and Temperature class. So it can access private members of both classes.
// This is not a member function only a friend function // This could defined outside of the function too friend Point operator+(cost Point &p, constint n){ returnPoint(p.m_x + n, p.m_y + n); }
friend Point operator+(constint n, const Point &p){ return p + n; }
friend Point operator+(const Point &p1, const Point &p2){ returnPoint(p1.m_x + p2.m_x, p1.m_y + p2.m_y); } };
intmain(int argc, char *argv[]){ Point p1(10, 20); Point p2(4, 5); Point p3 = p1 + p2 + 5;
p3.print();
return0; }
Using Normal Function
If there is no need to access private class data, operator overloading can be done as normal function.
Point operator+(const Point &p, constint n){ returnPoint(p.getX() + n, p.getY() + n); }
Point operator+(int n, const Point &p){ return p + n; }
Point operator+(const Point &p1, const Point &p2){ returnPoint(p1.getX() + p2.getX(), p1.getY() + p2.getY()); }
intmain(int argc, char *argv[]){ Point p1(10, 20); Point p2(4, 5); Point p3 = p1 + p2 + 5;
p3.print();
return0; }
Using Member Function
The assignment (=), subscript ([]), function call (()), and member selection (->) operators must be overloaded as member functions. IO operators(<< and >>) can’t be overloaded as memeber functions.
friend std::ostream& operator<< (std::ostream &out, const Point &p); friend std::istream& operator>> (std::istream &in, Point &p); };
// Overloading as friend function // Returning std::ostream so that it can be chained like std::cout << p1 << p2 std::ostream& operator<< (std::ostream &out, const Point &p){ out << "(" << p.m_x << ", " << p.m_y << ")"; return out; }
std::istream& operator>> (std::istream &in, Point &p){ in >> p.m_x >> p.m_y; return in; }
// Overloading as normal function Point operator+ (Point p, int n){ returnPoint(p.getX() + n, p.getY() + n); }
Point operator+ (int n, Point p){ return p + n; }
Point operator+ (Point p1, Point p2){ returnPoint(p1.getX() + p2.getX(), p1.getY() + p2.getY()); }
intmain(int argc, char *argv[]){ Point p1(10, 20); Point p2;
// () can only be overloaded as member function Point operator()(int n){ returnPoint(m_x + n, m_y + n); }
friend std::ostream& operator<< (std::ostream &out, const Point &p); };
// Overloading as friend function // Returning std::ostream so that it can be chained like std::cout << p1 << p2 std::ostream& operator<< (std::ostream &out, const Point &p){ out << "(" << p.m_x << ", " << p.m_y << ")"; return out; }
intmain(int argc, char *argv[]){ Point pnt(10, 20);
// Will add 5 to pnt.m_x, pnt.m_y and create new Point object. // Notce class object is called like function. std::cout << pnt(5) << "\n";
return0; }
Overloading Typecast
Typecast overloading can be done to convert between types.
// Overloading as friend function // Returning std::ostream so that it can be chained like std::cout << p1 << p2 std::ostream& operator<< (std::ostream &out, const Polar &p){ out << "(" << p.m_r << ", " << p.m_theta << ")"; return out; }
When copy initialization is used a copy constructor is used. By default compiler uses memberwise initialization if no copy constructor is provided. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
classXyz { private: int m_var; public: Xyz(int x): m_var(x){} };
intmain(void){ Xyz xy(10); // uses default initialization Xyz yz(xy); // Copy initialization // As there is no copy constructor provided, compiler will do a memberwise initialization }
Member functions of a class can access the private members ot the same class type. Here is an example with copy constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classXyz { private: int m_var; public: Xyz(int x): m_var(x){}
intmain(int argc, char *argv[]){ Hello h("hello"); Hello g(h); // Copy constructor will be used Hello i = Hello("gello"); // Copy constructor won't be used Hello k(Hello("gello")); // Copy constructor won't be used
Shallow copy means memberwise copying by the compiler if no copy constructor or overloaded assingment operator is provided.
The default copy constructor and default assignment operators do shallow copies, which is fine for classes that contain no dynamically allocated variables.
Classes with dynamically allocated variables need to have a copy constructor and assignment operator that do a deep copy.
Object Relationship
Composition and Aggregation
In both cases relationship between parent and child is ‘has a’.
Composition
The part (member) is part of the object (class)
The part (member) can only belong to one object (class) at a time
The part (member) has its existence managed by the object (class)
The part (member) does not know about the existence of the object (class)
Typically use normal member variables
Can use pointer members if the class handles object allocation/deallocation itself
Responsible for creation/destruction of parts
Aggregation
The part (member) is part of the object (class)
The part (member) can belong to more than one object (class) at a time
The part (member) does not have its existence managed by the object (class)
The part (member) does not know about the existence of the object (class)
Typically use pointer or reference members that point to or reference objects that live outside the scope of the aggregate class
Not responsible for creating/destroying parts
Association
The associated object (member) is otherwise unrelated to the object (class)
The associated object (member) can belong to more than one object (class) at a time
The associated object (member) does not have its existence managed by the object (class)
The associated object (member) may or may not know about the existence of the object (class)
Dependencies
A dependency occurs when one object invokes another object’s functionality in order to accomplish some specific task. This is a weaker relationship than an association, but still, any change to object being depended upon may break functionality in the (dependent) caller. A dependency is always a unidirectional relationship.
Container Classes
Hold and organize multiple instance of another type(class or fundamental type).
std::initializer_list
Used in container class’s constructor for list initialization.
Inheritance
Order of construction
Most base class constructed first and most derived class constructed last.
When a derived class is instanciated following things happen in order:
Memory for derived is set aside (enough for both the Base and Derived portions)
The appropriate Derived constructor is called
The Base object is constructed first using the appropriate Base constructor. If no base constructor is specified, the default constructor will be used.
The initialization list initializes variables
The body of the constructor executes
Control is returned to the caller
Constructors and initialization of derived classes
voididentify(void){ std::cout << "I am base\n"; } };
classDerived: public Base{ public: Derived(){}
voididentify(void){ std::cout << "I am derived\n"; } };
intmain(int argc, char *argv[]){ Derived *pd = newDerived(); // Pointer to base of derived object Base *pb{pd};
// Will call Derived::indentify() pd->identify();
// Will call Base::identify() pb->identify(); return0; }
Use case for this could be in functions which takes derived class as parameter. For each derived class a different functions have to be created. For example:
1 2 3 4 5 6 7
voidreport(Derived &d){ d.identify(); }
voidreport(AnotherDerived &ad){ ad.identify(); }
This problem can be solved using pointer/reference to base:
But the problem is in both cases Base::identify() will be called. As pointer to base only can see memebers from base. This problem can be solved using virtual functions.
Polymorphism
A virtual function is a special type of function that, when called, resolves to the most-derived version of the function that exists between the base and derived class. This capability is known as polymorphism. A derived function is considered a match if it has the same signature (name, parameter types, and whether it is const) and return type as the base version of the function. Such functions are called overrides.
If you want to call functions from base class in virtual function just use scope operator:
1 2 3 4
Derived d; Base *bp = &d;
std::cout << bp->Base::getName() << "\n";
Return type have to match between virtual functions.
Never use virtual function in constructors and destructors.
override and final Specifiers
A derived virtual function is only considered override if functino signature and return type matches exactly between the virtual functions. override specifier enforces virtualization of a function. If signature and return type doesn’t match the compiler will generate an error. If override is used, no need to specify virtual keyword.
Covariant Return Type
Destructors
In case of inheritance destructors should always make virtual. Specially if there is dynamically allocated memory involved. If a derived class is converted to a base class and then call delete, only base destructor will be called. If dynamic memory is allocated in derived class, this will leak memory.
Abstract Class, Pure Virtual Functions and Interface Class
Abstract class is a class wich is only used by the derived class. It can’t be instantiated anywhere else.
A pure virtual function has no body at all. It is meant to be redefined in derived classes. A class with pure virtual functions is an abstract class means it can’t be intantiated. A pure virtual function may or may not have a body.
1
virtualvoiddoSomething()= 0
In interface class has no member variables. All the functions are pure virtual.
Virtual Base Class
Single Base class is shared by the derived classes.
Solves diamond problem.
Most derived class is responsible for constructing the virtual base class.
class PoweredDevice { public: PoweredDevice(int power) { std::cout << "PoweredDevice: " << power << '\n'; } };
class Scanner: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class { public: Scanner(int scanner, int power) : PoweredDevice{ power } // this line is required to create Scanner objects, but ignored in this case { std::cout << "Scanner: " << scanner << '\n'; } };
class Printer: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class { public: Printer(int printer, int power) : PoweredDevice{ power } // this line is required to create Printer objects, but ignored in this case { std::cout << "Printer: " << printer << '\n'; } };
class Copier: public Scanner, public Printer { public: Copier(int scanner, int printer, int power) : PoweredDevice{ power }, // PoweredDevice is constructed here Scanner{ scanner, power }, Printer{ printer, power } { } };
Object Slicing
1 2 3 4 5 6 7 8 9 10
Derived d; Base b(d); // b will get the Base part from d. It is called object slicing
// Will call Base::doSomething() even if it is a virtual function b.doSomething()
Base &b(d);
// Will call Derived::doSomething if it is a virtual function as b in reference to d bp->doSomething()
In general avoid slicing
std::reference_wrapper
Dynamic Casting
Dynamic casing is used for downcasting.
Workaround for Friend Functions
Only member functions can be virtualized. So friend functions can’t be virtualized. For example:
#include<iostream> classBase { public: Base() {} // Here's our overloaded operator<< friend std::ostream& operator<<(std::ostream &out, const Base &b) { // Delegate printing responsibility for printing to member function print() return b.print(out); } // We'll rely on member function print() to do the actual printing // Because print is a normal member function, it can be virtualized virtual std::ostream& print(std::ostream& out)const { out << "Base"; return out; } }; classDerived : public Base { public: Derived() {} // Here's our override print function to handle the Derived case virtual std::ostream& print(std::ostream& out)constoverride { out << "Derived"; return out; } }; intmain() { Base b; std::cout << b << '\n'; Derived d; std::cout << d << '\n'; // note that this works even with no operator<< that explicitly handles Derived objects Base &bref = d; std::cout << bref << '\n'; return0; }
Templates
Function Template
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<iostream>
template <typename T> T add(T x, T y){ return x + y; }
#include<iostream> template <classT, int size> // size is the non-type parameter classStaticArray { private: // The non-type parameter controls the size of the array T m_array[size]; public: T* getArray(); T& operator[](int index) { return m_array[index]; } }; // Showing how a function for a class with a non-type parameter is defined outside of the class template <classT, int size> T* StaticArray<T, size>::getArray() { return m_array; } intmain() { // declare an integer array with room for 12 integers StaticArray<int, 12> intArray; // Fill it up in order, then print it backwards for (int count=0; count < 12; ++count) intArray[count] = count; for (int count=11; count >= 0; --count) std::cout << intArray[count] << " "; std::cout << '\n'; // declare a double buffer with room for 4 doubles StaticArray<double, 4> doubleArray; for (int count=0; count < 4; ++count) doubleArray[count] = 4.4 + 0.1*count; for (int count=0; count < 4; ++count) std::cout << doubleArray[count] << ' '; return0; }
Template Specialization
If an exception is needed to make for an specific type.
#include<stdio.h>/* Header files for the bellow functions */
1
FILE* fopen(char *fileName, char *mode);
Returns a FILE pointer associated with the file name or NULL if error occurs. Modes are r(read), w(write), a(append). There are three special file pointer; stdin(standard input), stdout(standard output), stderr(standard error).
1
intgetc(FILE *filePointer);
Returns next character from the file stream referred to by filePointer. It returns EOF if end of file or error occurs.
1
intputc(int c, FILE *filePointer);
Writes character c to the file referred to by filePointer. Retuens the character written or EOF if error occurs.
char *fgets(char *line, int MAX_CHAR, FILE *filePointer);
Reads the next line from the file referred to by filepointer into char array line. MAX_CHAR - 1 characters will be read. Returns pointer to the line or NULL if EOF or error occurs.
1
intfputs(char *line, FILE *filePointer);
Writes a string to a file. Returns EOF if error occurs, zero otherwise.
1
intremove(constchar *fileName);
Removes fileName from file system. Returns non zero if attempt fails
Rename oldFileName to newFileName. Returns non zero if attempt fails.
1
FILE* tmpfile(void);
Creates a temporary file of mode wb+. It will be removed automatically when the file is closed.
1
intfclose(FILE *filePointer);
Closes a file.
Error Handling
1 2
intferror(FILE *filePointer); /* Returns non zero if an error occurs */ intfeof(FILE *filePointer); /* Return non zero if eof occurs */
1
voidperror(FILE *filePointer, chars *s);
Prints interactive error message to filePointer if no argument specified Or s.
Low Level Access
1
#include<fcntl.h>/* Header file for the bellow functions */
1
intopen(char *name, int flags, int perms);
Returns an integer associated with the file, which is called a file descriptor. When shell runs a program three files are open automatically the standard input, standard output and standard error. Their associated file descriptors are 0, 1 & 2.
Here are some flags:
1 2 3
O_RDONLY - Open file in read only mode O_WRONLY - Open file in write only mode O_RDWR - Open file in read / write mode
Perm is the unix file permission specified as a 3 digit octal.
1
intcreate(char *name, int perms);
Creates a file using name and returns a file descriptor associated with it. Returns -1 if fails.
1
#include<unistd.h>/* Header file for the bellow functions */
1
intread(int fileDescriptor, char *buffer, int n);
Reads n bytes from a file associated with fileDescriptor into buffer array. Returns number of bytes transferred. A return value of zero indicates EOF and -1 indicates an error.
1
intwrite(int fileDescriptor, char *buffer, int n);
Writes n bytes from buffer array to a file associated with fileDescriptor. It returns number of bytes written.
1
longlseek(int fileDescriptor, long offset, int origin);
Set the current position of the file to offset which is taken relative to the location specified by origin. Orgigin can be 0, 1 or 2 to specify that offset is to be measured from the begaining, current position or end of the file.
1
intunlink(constchar *path);
Removes a file. Returns 0 upon success otherwise -1.
1
intclose(int fileDescriptor);
Closes a file.
User Defined Types
Structure
Creating a structure:
1 2 3 4 5
structpacket{ int size; double length; double breadth; };
intmain(){ /* Can be treated like regular variable */ enumTypet;
/* Value assignment can be one of the enum members */ t = INT;
/* Can be used directly without a enumerated variable */ if(t == INT){ printf("This is an integer.\n"); } elseif(t == DOUBLE){ printf("This is a double.\n"); } elseif(t == CHAR){ printf("This is a character variable.\n"); }
return0; }
Bit Fields
Bit field is used to pack several variables into a machine word. Bit fields are declared just like regular structures. But variable type have to be unsigned int and bit length of each variable is specified using : operator.
1 2 3 4 5 6
structflags{ unsignedint is_color:1// 1 bit length unsignedint is_sound:1// 1 bit length unsignedint is_open:1// 1 bit length unsignedint status:4// 4 bit length };
Typedefs
Typedefs are used to give an alias for a type.Structure:
1
typedef TYPE ALIAS
Example:
1
typedefdoubledist_t; // dist_t can be used instead of double