Home C++
Post
Cancel

C++

1
2
3
4
5
6
7
#include <iostream>

int main()
{
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Namespaces

To avoid using std:: all the time you can specify the namespace at the top of the file:

1
2
  #include <iostream>
  using namespace std;

Using the namespace declaration is not recommended because it imports everything. Instead, you can import only the needed parts of the namespace:

1
2
3
4
5
  #include <iostream>
  using std::cout;
  using std::cin;
  using std::endl;
  using std::string;

System

With system() you can execute a command in the shell:

1
2
3
using std::system;

system("bash script.sh");

Every time you call this function a new shell is created so you have to combine commands with &&

Data Types

1
2
3
4
5
6
7
string name = "Saracen"; //string
char gender = 'm'; //char
int age = 20; //int
bool older18 = true; //bool
float averageGrade = 4.0f; //float
double balance = 3535664675.757; //double
int arrname[10] = {0,1,2,3,4,5,6,7,8,9}; //array

Operators

Arithmetic

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
++Incrementi++
Decrementi--

Assignment

OperatorExampleSame As
=x = 5x + y
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5

Comparison

OperatorNameExample
==equal tox == y
!=not equal tox != y
>greater thanx > y
<less thanx < y
>=greater than or equal tox >= y
<=less than or equal tox <= y

Logical

OperatorNameDescriptionExample
&&ANDreturns true if both statements are truex < 5 && x < 10
||ORreturns true if one of the statements is truex < 5 || x < 4
!NOTreverse the result, returns false if the result is true!(x < 5 && x < 10)

Bitwise

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both bits are 15 & 1
|ORSets each bit to 1 if one of two bits is 15 \| 1
^XORSets each bit to 1 if only one of two bits is 15 ^ 1
~NOTInverts all the bits~5
«Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off5 << 1
»Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off5 >> 1

In and Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// print to console
cout << "Hello, World!" << endl;
//same as
cout << "Hello, World!\n";
//print variable
cout << "my name is " << username << endl;
// get user input
string name;
int age; 
cin >> name;
// get multiple input values
// first input space second input
cin >> name >> age;

Casting

change the data type of a variable

1
2
x = 3.14; //double
y = (int)x; //int

Arrays

1
2
3
4
5
6
int array[] = {1, 2, 3, 4, 5, 6}; //you can also use int array[6] to specify the size
int arraySize = sizeof(array) / sizeof(array[0]); //get size of array

for (auto item : items) {  // iterate array or list
    cout << item << endl;
}

Flow Control

if else statement

1
2
3
4
5
6
7
8
int n;
cout << "enter number ";
cin >> n;
if (n%2 == 0) {
    cout << "the mumber is even" << endl;
} else {
    cout << "the mumber is odd" << endl;
}

switch statement

1
2
3
4
5
6
7
8
9
10
11
int day = 4;
switch (day) {
  case 6:
    cout << "Today is Saturday";
    break;
  case 7:
    cout << "Today is Sunday";
    break;
  default:
    cout << "Looking forward to the Weekend";
}

if there is no “break” the next case will be executed too

for loop

1
2
3
for (int i = 0; i < 5; i++) {
  cout << i ;
}

auto for loop

1
2
3
for (auto item : items) {  // iterate array or list
  cout << item << endl;
}

You can specify the type instead of auto.
You can also use auto to initialise a variable.

while loop

1
2
3
4
5
int i = 0;
while (i < 5) {
  cout << i;
  i++;
}

do while loop

1
2
3
4
5
int i = 0;
do {
  cout << i;
  i++;
} while (i < 5);

gets executed at least once

break statement

1
2
3
4
5
6
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  cout << i;
}

break statement breaks the loop

continue statement

1
2
3
4
5
6
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  cout << i;
}

continue statement skips the current iteration

functions

1
2
3
4
5
6
7
8
int myFunction(int x, int y);

int main () {
    //code
}
int myFunction(int x, int y) {
    return x + y;
}

You can also define the function before the main function and implement it after the main function. This way you have an overview of all functions in the beginning of the code.

default parameters

1
2
3
int myFunction(int x, int y = 5) {
    return x + y;
  }

You can set a default value for a parameter so you don’t have to pass it every time
you can overwrite the default value by passing a value

Exceptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    
try {
    int age = 21;
    if (age >= 16) {
        cout << "Access granted - you are old enough.";
    }
    else {
        throw(age);
    }
}
catch (int age) {
    cout << "Access denied - You must be at least 18 years old.\n";
    cout << "Age is: " << age;
}

Structs

1
2
3
4
5
6
// Create structure variables and assign values (optional)
struct{
  int number;
  string text;
} myStruct = {0,"hello"}, 
  myStruct2 = {1,"world"};

You van initialize struct variables with default values, too. {: .prompt-info }

Access struct variables with .

1
2
3
myStruct.number = 1;
myStruct.text = "hello";
cout << myStruct.number << " " << myStruct.text << endl;

You can also give the struct a name and use it like a data type

1
2
3
4
5
6
7
8
9
10
11
12
struct Book{
  string title;
  int year;
  int pages;
  bool isHardcover;
};

int main(){
  Book Skulduggery1 = {"Skulduggery Pleasant", 2007, 400, true};
  cout << Skulduggery1.title << endl;
  return 0;
}

Templates

Templates can stand for any datatype to awoid function overloading

1
2
3
4
5
6
template <typename T>                    
void swapValue(T &a, T &b){
    T temp = a;
    a = b;
    b = temp;
}

OOP

Classes

everything protected can only be accessed inside the class and subclasses
everything private can only be accessed inside the class
you can use getter and setter to access private and protected variables outside the class
everything public can be accessed everywhere
this->name is the same as this.name in Java or self.name in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <list>
class YouTubeChannel{
protected:
    string name;
    string ownerName;
    int subscribersCount;
    list <string> publishedVideoTitles;
public:
    YouTubeChannel(string name, string ownerName){
        this->name = name;
        this->ownerName = ownerName;
        this->subscribersCount = 0;
    }
    string getName(){
        return this->name;
    }
    string setName(string name){
        this->name = name; 
    }
};

int main() {
    // create object of class YouTubeChannel
    YouTubeChannel ytChannel("Saracen", "Saracen");
    ytChannel.setName("Saracen");
    cout << ytChannel.getName();
}

Enheritance

1
2
3
4
5
6
7
8
9
10
// CookinChannel inherits from YouTubeChannel (superclass)
class CookingChannel : public YouTubeChannel{
public:
    // use constructor of YouTubeChannel (super constructor)
    CookingChannel(string name, string ownerName):YouTubeChannel(name, ownerName){}

    void practice(){
        cout << OwnerName << " is practicing how to cook" << endl;
    }
};
This post is licensed under CC BY 4.0 by the author.