Notes I took while learning C++.
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
// -> Single line comment
/**/ -> Multi line comment
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
Power of 10 with "e" -> "35e3" or "12E4"
Display character with ASCII codes.
#include <string>
typeString + typeString
OR
typeString.append(typeString)
typeString[n] - First character is 0
typeString[n] = 'character';
variable.length();
// OR
variable.size()
// You can use length() and size() everything
std::type variableName = value;
std::int x = 10, y = 5;
const std::type variableName = value;
std::cin >> variable; -> Displays the word before you type space.
std::getline (std::cin, variable);
max(variable1, variable2) - Determines which one is bigger
min(variable1, variable2) - Determines which one is smaller
#include <cmath>;
cout << sqrt(64);
cout << round(2.6);
cout << log(2);
#include <cmath>; // Reseach for the cmath header file
+ NOTE: Strings are concatenated numbers are added.
-
/
*
%
++
--
=
+=
-+
*=
/=
%=
&=
|=
^=
>>=
<<=
==
!=
>
<
>=
<=
&& - Logical AND
|| - Logical OR
! - Logical NOT
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
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"
}
variable = (condition) ? expressionTrue : expressionFlase;
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
}
while (condition) {
// Executed as long as condition is true
}
do {
// Executed no matter what; at least 1 time
} while (condition); // Loops again if condition is true
for (statement1; statement2; statement3) {
// Loops for a certain condition
}
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
}
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
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 - Stops the process <br>
continue - Skips a specified process
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
You don't have to specify the array size.
type arrayName[1D][2D];
arrayName[1D][2D];
arrayName[1D][2D] = newValue;
int numbers[2][4] = {
{5, 2, 75, 24},
{37, 35, 23, 56}
};
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
for (int i = 0; i < 2; i++) { // First Dimension
for (int j = 0; j < 4; j++) { // Second Dimension
cout << letters[i][j] << "\n";
}
}
struct { // Structure initialisation
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure, myStructure2; // Structure variables (Decide yourself how much you need)
struct structsName {
type variableName;
type variableName;
};
structsName variableName; // Declare Data type
variableName.structsVariable; // Access variables inside of structs
variableName.structsVariable = newValue; // Change variable values inside of the struct
structureName.varibleName;
type variable1 = value;
string &variable2 = variable1;
string food = "Pizza";
string* ptr = &food;
string* mystring; // Preferred
string *mystring;
string * mystring;
string food = "Pizza"; // Variable initialisation
string* ptr = &food; // Pointer initialisation
cout << *ptr << "\n"; // Dereferencing
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";
returnType functionName(parameter1, parameter2) { // Initialisation
// Will be executed if the function is called // Definition
}
Inside of the main function. As many times as you like.
int main() {
functionName();
functionName();
return 0;
}
// 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!";
}
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!
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;
}
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;
}
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;
}
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
NOTE: Multiple functions can have the same name as long as the number and/or type of parameters are different!
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;
}
class className { // Initialisation
public: // Access specifier
// Public attributes
}
className objectName;
objectName.attributeName;
objectName.attributeName = newValue;
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
// Code for the method
}
};
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
}
class className { // Initialisation
public: // Access specifier
// Public attributes / constructor
className(type parameter1, type parameter2) {
// Constructor have to have the same name as the class
}
}
int main() {
className(type parameter); // Have to have all required parameters
}
class className {
className(type parameter);
}
className::constructorName(type parameter) {
// Code
}
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.
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.
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;
}
};
// Parent class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Child class
class Car: public Vehicle {
public:
string model = "Mustang";
};
// 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 {
};
// 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 {
};
// 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;
}
};
// 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";
}
};
#include <iostream>
#include <fstream>
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
std::ofstream fileName("file-path");
// Write
fileName << "You can write nearly everything into a file";
// Close
fileName.close();
// 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();
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
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
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
}