Skip to content

Instantly share code, notes, and snippets.

@VenenJean
Last active December 27, 2022 09:07
Show Gist options
  • Save VenenJean/8e8a0c7fcaee8713d8aaf7230b28d6b6 to your computer and use it in GitHub Desktop.
Save VenenJean/8e8a0c7fcaee8713d8aaf7230b28d6b6 to your computer and use it in GitHub Desktop.

C++ Notes

Notes I took while learning C++.

Escape codes

std::endl; -> No escape code | Adds a new line and flushes the buffer
std::cout << "\n"; -> New line | Recommended in most cases instead of "std::endl"
std::cout << "\t"; -> Horizontal Tab
std::cout << "\\"; -> Backslash
std::cout << "\""; -> Double quote

Comments:

// -> Single line comment
/**/ -> Multi line comment

Data types - Variables:

int    -    Integers (Whole number) - 2 or 4 byte
float  -    floating point number   - 4 bytes       - precision 6-7 decimal digits
double -    floating point number   - 8 bytes       - precision 15 decimal digits
char   -    Single Character        - 1 bytes       - surrounded by single quotes
string -    Stores strings (Text)                   - surrounded by double quotes
bool   -    true (1) or false (0)   - 1 byte

Float numbers

Power of 10 with "e" -> "35e3" or "12E4"

Char

Display character with ASCII codes.

String:

#include <string>

Concatenation:

typeString + typeString
OR
typeString.append(typeString)

Access/Change character:

typeString[n] - First character is 0
typeString[n] = 'character';

Get length:

variable.length();
// OR
variable.size()
// You can use length() and size() everything

Initialisation - Multiple:

std::type variableName = value;
std::int x = 10, y = 5;

Constants:

const std::type variableName = value;

User Input:

std::cin >> variable; -> Displays the word before you type space.
std::getline (std::cin, variable);

Mathematics:

Basic:

max(variable1, variable2) - Determines which one is bigger
min(variable1, variable2) - Determines which one is smaller

Header file:

#include <cmath>;
cout << sqrt(64);
cout << round(2.6);
cout << log(2);

Advanced:

#include <cmath>; // Reseach for the cmath header file

Operators:

Simple:

+ NOTE: Strings are concatenated numbers are added.
-
/
*
%
++
--

Assignment:

=
+=
-+
*=
/=
%=
&=
|=
^=
>>=
<<=

Comparison (always returns a boolean value):

==
!=
>
<
>=
<=

Logical:

&& - Logical AND
|| - Logical OR
!  - Logical NOT

Conditional statements:

if          - Executed if specific condition is "true"
else        - Executed if the same condition is "false"
else if     - New conditions test if first condition was "false"
switch      - specify many alternative blocks to execute

Syntax

if Statement:
if (condition) {
    // Executed if condition if "true"
} else if (condition) {
    // Executed if 1 condition is "false" and this condition is "true"
} else {
    // Executed if condition is "false"
}

Shorthand

variable = (condition) ? expressionTrue : expressionFlase;

Switch:

switch(expression) {
    case x:
        // Code executed is case "x" is true
        break;
    case y:
        // Code executed is case "x" is true
        break;
    default:
    // Executed no matter what
}

Loops:

Syntax while-loop

while (condition) {
    // Executed as long as condition is true
}

Syntax do-while-loop

do {
    // Executed no matter what; at least 1 time
} while (condition); // Loops again if condition is true

Syntax for-loop

for (statement1; statement2; statement3) {
    // Loops for a certain condition
}

NOTE: Loop can loop forever! Be aware of it!

Statement 1: Executed (one time) before the execution of the code.
Statement 2: Defines the condition for the loop.
Statement 3: Is executed (every time) after the code has been executed.

for (type variableName : arrayName) {
    // Loops through a collection of data
}

Example (for-loop):

for (int i = 0; i < 5; i++) {
  cout << i << "\n";
}

Nested loops:

The "inner loop" will be executed one time for each iteration of the "outer loop":

// Outer loop
for (int i = 1; i <= 2; ++i) {
  cout << "Outer: " << i << "\n"; // Executes 2 times
  // Inner loop
  for (int j = 1; j <= 3; ++j) {
    cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
  }
}

Break and Continue:

break - Stops the process <br>
continue - Skips a specified process

Arrays - Declare/Access/Change/Size:

type arrayName[size]; = {"value1", "value2", etc.};
arrayName[itemNum]; -> First value is 0
arrayName[itemNum]; = newItem;
sizeof(arrayName); -> Returns size in bytes
sifeof(arrayName); / sizeof(arrayType); -> Array size in elements

Array size:

You don't have to specify the array size.

Multi-Dimensional Arrays:

type arrayName[1D][2D];

Access/Change:

arrayName[1D][2D];
arrayName[1D][2D] = newValue;

NOTE: You can add as much dimensions as you like!

Example:

2D array:

int numbers[2][4] = {
    {5, 2, 75, 24},
    {37, 35, 23, 56}
};

3D arrays:

string letters[2][2][2] = {
  {
    { "A", "B" },
    { "C", "D" }
  },
  {
    { "E", "F" },
    { "G", "H" }
  }
};

Loop through:

for (int i = 0; i < 2; i++) { // First Dimension
  for (int j = 0; j < 4; j++) { // Second Dimension
    cout << letters[i][j] << "\n";
  }
}

Structures(collection of data/variables):

struct {                      // Structure initialisation
  int myNum;                  // Member (int variable)
  string myString;            // Member (string variable)
} myStructure, myStructure2;  // Structure variables (Decide yourself how much you need)

Named structures:

struct structsName {
  type variableName;
  type variableName;
};

Use it:

structsName variableName; // Declare Data type
variableName.structsVariable; // Access variables inside of structs
variableName.structsVariable = newValue; // Change variable values inside of the struct

Access:

structureName.varibleName;

References:

Example:

type variable1 = value;
string &variable2 = variable1;

Pointers (stores the memory address as it's value):

Declare:

string food = "Pizza";
string* ptr = &food;

Different declaration ways:

string* mystring; // Preferred
string *mystring;
string * mystring;

Dereference:

string food = "Pizza";  // Variable initialisation
string* ptr = &food;    // Pointer initialisation
cout << *ptr << "\n";   // Dereferencing

Modify the Pointer value:

NOTE: If you change the pointers value the original variable won't be affected!

Example:

string food = "Pizza";
string* ptr = &food;
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";

Functions

Initialisation

returnType functionName(parameter1, parameter2) { // Initialisation
    // Will be executed if the function is called // Definition
}

Calling

Inside of the main function. As many times as you like.

int main() {
    functionName();
    functionName();
    return 0;
}

Rule

Declare function before the main function to call it.

Sort your functions

Example

// Function declaration
void myFunction();
// The main method
int main() {
  myFunction();  // call the function
  return 0;
}
// Function definition
void myFunction() {
  std::cout << "I just got executed!";
}

Default parameter

returnType functionName(parameter = DefaultValue) {}

NOTE: You can add as much parameters as you like! The function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order!

Return type

The Function have to have the same return type as the returned value. If nothing is returned the return type have to be "void".

int main() {
    return 0;
}

Pass By Reference

void swapNums(int &x, int &y) { // Receiving references
  int z = x;
  x = y;
  y = z;
}
int main() {
  // Declaring integer variables
  int firstNum = 10;
  int secondNum = 20;
  cout << "Before swap: " << "\n";
  cout << firstNum << secondNum << "\n";
  // Call the function, which will change the values of firstNum and secondNum
  swapNums(firstNum, secondNum);
  cout << "After swap: " << "\n";
  cout << firstNum << secondNum << "\n";
  return 0;
}

Pass arrays as function Parameters

void myFunction(int myNumbers[5]) { // Array as parameter; size is not required
  for (int i = 0; i < 5; i++) { // Loops through the array
    cout << myNumbers[i] << "\n";
  }
}
int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50}; // Declaring an array
  myFunction(myNumbers); // calling myFunciton and passing the array as a parameter
  return 0;
}

Function overloading

int plusFunc(int x, int y) {
  return x + y;
}
double plusFunc(double x, double y) {
  return x + y;
}

NOTE: Be aware of the data types!

NOTE: Multiple functions can have the same name as long as the number and/or type of parameters are different!

Recursion (calling a function inside itself)

int password() {
  std::cin >> pass;
  if (pass.length() < 10) { // Checking for length
    std::cout << "Try again.";
    password(); // If length is smaller than 10 is will repeat
  }
}
int main() {
  password();
  cout << result; // Printing out result
  return 0;
}

Classes

Initialisation

class className { // Initialisation
public: // Access specifier
    // Public attributes
}

Object

Declaration

className objectName;

Access/set attributes value

objectName.attributeName;
objectName.attributeName = newValue;

NOTE: You can create as much objects as you want!

Class Methods

class MyClass {        // The class
  public:              // Access specifier
    void myMethod() {  // Method/function defined inside the class
      // Code for the method
    }
};

NOTE: Function != Method!

Definition outside

class MyClass {        // The class
  public:              // Access specifier
    void myMethod(int parameter);   // Method/function declaration
};

// Method definition outside of the class
void MyClass::myMethod(int parameter) {
  // Note that the parameter have to be the same
}

Constructor

Initialisation

class className { // Initialisation
public: // Access specifier
    // Public attributes / constructor
    className(type parameter1, type parameter2) {
        // Constructor have to have the same name as the class
    }
}

Usage

int main() {
    className(type parameter); // Have to have all required parameters
}

Definition outside

class className {
    className(type parameter);
}

className::constructorName(type parameter) {
    // Code
}

NOTE: Be aware of all the parameter!

Access Specifiers

public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from outside the class (usage only inside the class)
protected - members cannot be accessed from outside the class, but they can be accessed in inherited classes.

NOTE: Access private members of a class using public methods inside the same class!

TIP: It is considered good practice to declare your class attributes as private (as often as you can). This will reduce the possibility of yourself (or others) to mess up the code. This is also the main ingredient of the Encapsulation concept.

Encapsulation

Get/Set Methods

class Employee {
  private:
    // Private attribute
    int salary;

  public:
    // Sets private salary to s
    void setSalary(int s) {
      salary = s;
    }
    // Returns the salary
    int getSalary() {
      return salary;
    }
};

NOTE: Encapsulation provides better data security!

Inheritance

Usage

// Parent class
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// Child class
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

Multilevel Inheritance

// Base class (parent)
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Derived class (child)
class MyChild: public MyClass {
};

// Derived class (grandchild)
class MyGrandChild: public MyChild {
};

Multiple Inheritance

// Base class
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Another base class
class MyOtherClass {
  public:
    void myOtherFunction() {
      cout << "Some content in another class." ;
    }
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

Inheritance access

// Base class
class Employee {
  protected: // Protected access specifier
    int salary;
};

// Derived class
class Programmer: public Employee {
  public:
    // Access protected attributes in inherited classes
    void setSalary(int s) {
      salary = s;
    }
    int getSalary() {
      return salary;
    }
};

Polymorphism(many forms)

Reusing classes to change some details
// Base class
class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound \n";
    }
};

// Derived class
class Pig : public Animal {
  public:
    // Overriding this method to match the case
    void animalSound() {
      cout << "The pig says: wee wee \n";
    }
};

// Derived class
class Dog : public Animal {
  public:
    // Overriding this method to match the case
    void animalSound() {
      cout << "The dog says: bow wow \n";
    }
};

Files

Required Header Files

#include <iostream>
#include <fstream>

Important classes

std::ofstream - Creates and writes to files
std::ifstream - Reads from files
std::fstream - A combination of ofstream and ifstream: creates, reads and writes to files

Create - Write - Close file

// Create
std::ofstream fileName("file-path");

// Write
fileName << "You can write nearly everything into a file";

// Close
fileName.close();

NOTE: Closing files cleans up unnecessary memory.

Read file

// Store the output
string myText;

// Reads the file
std::ifstream MyReadFile("filename.txt");

// Looping through the file and reading it line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  std::cout << myText;
}

// Close the file
MyReadFile.close();

Exceptions

Keywords

try - tests for errors while being executed
throw - throws an exception when a problem is detected, which lets us create a custom error
catch - executed if an error occurs

NOTE: try and catch keywords some in pairs!

Syntax:

try {
  // Block of code to try
  throw exception; // Throw an exception when a problem arise
}
catch () {
  // Block of code to handle errors
}

Example:

try {
  int age = 15;
  if (age >= 18) {
    std::cout << "Access granted - you are old enough.";
  } else {
    throw (age); // 1. Throwing exception about the "error" (not really an error)
  }
}
catch (int myNum) { // 2. Have to be the same type as 1.
  std::cout << "Access denied - You must be at least 18 years old.\n";
  std::cout << "Age is: " << myNum; // <- Same value as the age variable
}

NOTE: Create custom error codes by replacing the "throw(age)" with "throw(errorCode)"!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment