# C++ language Tutorial
## Basic syntax
```cpp=
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! << endl";
return 0;
}
```
```cpp=
#include <iostream>
int main() {
std::cout << "Hello World! << endl";
return 0;
}
```
```cpp=
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Type a number: ";
cin >> x;
cout << "Your number is: " << x;
return 0;
}
```
### Comments
```cpp=
#include <iostream>
using namespace std;
int main() {
// This is a comment.
/* This is a comment 1.
This is a comment 2. */
return 0;
}
```
## Data type
Common built-in data types in C++ language
| Data type | Bytes | Description |
| :-------- | :---: | :---------- |
| bool | 1 | Stores true or false values. |
| char | 1 | Stores a single character/letter/number, or ASCII values. |
| string | | Stores text, such as "Hello World". String values are surrounded by double quotes. |
| int | 2 or 4 | Stores whole numbers, without decimals. |
| float | 4 | Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits. |
| double | 8 | Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
. |
### Constants
When we do not want others to override existing variable values, use the const keyword. (this will declare the variable as "constant", which means unchangeable and read-only)
```cpp=
const float PI = 3.14;
PI = 10; // error: assignment of read-only variable 'PI'
```
### Scientific numbers
```cpp=
float f1 = 12e4;
double d1 = 12E4;
cout << f1;
cout << d1;
```
### String
To use strings, we must include an additional header file in the source code, the `<string>` library.
```cpp=
#include <string>
string greeting = "Hello";
```
To get the length of a string, use the length() function `length()` or `size()`.
```cpp=
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
cout << "The length of the txt string is: " << txt.size();
```
`cin` considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only display a single word (even if you type many words). We often use the `getline()` function to read a line of text. It takes cin as the first parameter, and the string variable as second.
```cpp=
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
```
## Operators
C++ divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
### Arithmetic operators
| Operator | Name | Description |
| -------- |:---- | :---------- |
| + | Addition | Adds together two values. |
| - | Subtraction | Subtracts one value from another. |
| * | Multiplication | Multiplies two values. |
| / | Division | Divides one value by another. |
| % | Modulus | Returns the division remainder. |
| ++ | Increment | Increases the value of a variable by 1. |
| -- | Decrement | Decreases the value of a variable by 1. |
### Assignment operators
Assignment operators are used to assign values to variables. We use the assignment operator (=) to assign the value 10 to a variable called x.
```cpp=
int x = 10;
x += 5;
```
### Comparison operators
| Operator | Name |
| -------- |:---- |
| == | Equal to |
| != | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
### Logical operators
| Operator | Name | Description |
| -------- |:---- | :---------- |
| && | Logical and | Returns true if both statements are true. |
| \|\| | Logical or | Returns true if one of the statements is true. |
| ! | Logical not | Reverse the result, returns false if the result is true. |
### Bitwise operators
## Conditions
```cpp=
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
```
### Short Hand If...Else (Ternary Operator)
```cpp=
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
```
### Switch
```c
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
```
## Loop
### While loop
```cpp=
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
```
```cpp=
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
```
### For loop
```cpp=
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
```
```cpp=
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
```
### `break`, `continue`
## Arrays
```cpp=
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
```
```cpp=
string cars_1[] = {"Volvo", "BMW", "Ford"};
string cars_2[3] = {"Volvo", "BMW", "Ford"};
```
```cpp=
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
```
```cpp=
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
```
```cpp=
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
```
## Structure
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
C: https://hackmd.io/guFyCtkBTdi77dBRmruavw?view
## Pointers
### References
```cpp=
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
```
### Memory address
```cpp=
string food = "Pizza";
cout << &food; // Outputs 0x6dfed4
```
C: https://hackmd.io/guFyCtkBTdi77dBRmruavw?view
## Functions
```c=
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
cout << result;
return 0;
}
```
```c=
// Function declaration
int myFunction(int, int);
// The main method
int main() {
int result = myFunction(5, 3); // call the function
cout << result;
return 0;
}
// Function definition
int myFunction(int x, int y) {
return x + y;
}
```
### Call (Pass) by reference
In the examples from the previous page, we used normal variables when we passed parameters to a function. We can also pass a reference to the function. This can be useful when we need to change the value of the arguments.
```cpp=
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
```
```cpp=
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
```
#### Compare
```cpp=
void CallByValue_Plus(int a) {
a++;
cout << "a in the CallByValue_Plus: " << a << endl;
cout << "address of a in the CallByValue_Plus: " << &a << endl;
}
void CallByAddress_Plus(int* b) {
(*b)++;
cout << "*b in the CallByAddress_Plus: " << *b << endl;
cout << "address of b in the CallByAddress_Plus: " << &b << endl;
}
void CallByReference_Plus(int& c)
{
c++;
cout << "c in the CallByReference_Plus: " << c << endl;
cout << "address of c in the CallByReference_Plus: " << &c << endl;
}
int main() {
int a = 10;
int b = 100;
int c = 1000;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "c: " << c << endl;
CallByValue_Plus(a);
CallByAddress_Plus(&b);
CallByReference_Plus(c);
cout << "After CallByValue_Plus(a), a in the main "<< a << endl;
cout << "After CallByAddress_Plus(b), b in the main: " << b << endl;
cout << "After CallByReference_Plus(c), c in the main: " << c << endl;
cout << "After CallByValue_Plus(a), address of a in the main " << &a << endl;
cout << "After CallByAddress_Plus(b), address of b in the main: " << &b << endl;
cout << "After CallByReference_Plus(c), address of c in the main: " << &c << endl;
system("pause");
return 0;
}
```
ref:
- [1](https://wayne265265.pixnet.net/blog/post/112556555-%E3%80%90%E6%95%99%E5%AD%B8%E3%80%91call-by-value%2C-call-by-address%2C-call-by-referenc)
- [2](https://dotblogs.com.tw/Ace_Dream/2016/06/01/callbyvalue_callbyaddress_callbyreference)
### Function overloading
```cpp=
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
```
## Template
A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types.
There are two ways we can implement templates:
- Function Templates
- Class Templates
### Function template
Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray().
```cpp=
#include <iostream>
using namespace std;
//normal function:
int myAdd(int a, int b) {
return a + b;
}
//function template
template <typename T> T myAdd_2(T a, T b) {
return a + b;
}
// usually type: two lines
template <typename T>
T myAdd_3(T a, T b) {
return a + b;
}
int main() {
int a = 1, b = 2;
cout << myAdd_3(a, b) << endl;
return 0;
}
```
```cpp=
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2) {
return (num1 + num2);
}
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
// calling with double parameters
result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;
return 0;
}
```
### Class template
Class Templates like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
```cpp=
#include <iostream>
using namespace std;
// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;
public:
// Number(T n) : num(n) {} // constructor
Number(T n) {
num = n;
}
T getNum() {
return num;
}
};
int main() {
// create object with int type
Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);
cout << "int Number = " << numberInt.getNum() << endl;
cout << "double Number = " << numberDouble.getNum() << endl;
return 0;
}
```
ref:
[https://www.rocksaying.tw/archives/3641717.html](https://www.rocksaying.tw/archives/3641717.html)
[C++ Function Template - Programize](https://www.programiz.com/cpp-programming/function-template)
[C++ Class Templates - Programize](https://www.programiz.com/cpp-programming/class-templates)
## Object-Oriented Programming (OOP)
### Introduction
Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.
Object-oriented programming has several advantages over procedural programming:
- OOP is faster and easier to execute
- OOP provides a clear structure for the programs
- OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
- OOP makes it possible to create full reusable applications with less code and shorter development time
- Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.
A class is a template for objects, and an object is an instance of a class. When the individual objects are created, they inherit all the variables and functions from the class.
C++ is an object-oriented programming language.
### Classes, objects, methods
Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a "blueprint" for creating objects.
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
- Inside class definition
- Outside class definition
We access attributes and methods by creating an object of the class and using the dot syntax (.).
To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by specifiying the name of the class, followed the scope resolution `::` operator, followed by the name of the function.
```cpp=
class MyClass { // The class
public: // Access specifier
int myNum_1; // Attribute (int variable)
int myNum_2; // Attribute (int variable)
string myString; // Attribute (string variable)
public:
void myMethod_1() { // Method/function defined inside the class
cout << myNum_1 + myNum_2 << "\n";
}
public:
void myMethod_2();
public:
int myMethod_3(int myNum_3, int myNum_4);
};
// Method/function definition outside the class
void MyClass::myMethod_2() {
cout << "Hello World!" << "\n";
cout << myNum_1 - myNum_2 << "\n";
}
int MyClass::myMethod_3(int myNum_3, int myNum_4) {
return myNum_3 + myNum_4;
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myNum_1 = 15; // Access attributes and set values
myObj.myNum_2 = 6;
myObj.myString = "Some text";
myObj.myMethod_1(); // Call the method
myObj.myMethod_2();
cout << myObj.myMethod_3(8, 3) << "\n"; // Call the method with an argument
return 0;
}
```
### Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is created. To create a constructor, use the same name as the class, followed by parentheses ().
The constructor has the same name as the class, it is always public, and it does not have any return value.
```cpp=
class MyClass {
public:
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
```
#### Constructor parameters
```cpp=
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
```
#### Outside class definition
```cpp=
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
```
### Access Specifiers
In C++, there are three access specifiers:
- public - members are accessible from outside the class.
- private - members cannot be accessed (or viewed) from outside the class.
- protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
#### `private`
```cpp=
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
```
#### Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public `get` and `set` methods.
```cpp=
class Employee {
private:
int salary; // Private attribute
public:
void setSalary(int s) { // Setter
salary = s;
}
int getSalary() { // Getter
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(5);
cout << myObj.getSalary();
return 0;
}
```
```cpp=
class Employee {
protected:
int salary; // Protected attribute
public:
void setSalary(int s) { // Setter
salary = s;
}
int getSalary() { // Getter
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(5);
cout << myObj.getSalary();
return 0;
}
```
#### `protected`
```cpp=
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50);
myObj.bonus = 150;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
```
### Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
- derived class (child) - the class that inherits from another class
- base class (parent) - the class being inherited from
To inherit from a class, use the `:` symbol.
It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
```cpp=
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
```
#### Multilevel inheritance
A class can also be derived from one class, which is already derived from another class.
```cpp=
// 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 {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
```
#### Multiple inheritance
A class can also be derived from more than one base class, using a comma-separated list.
```cpp=
// 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 {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
```
### Polymorphism
```cpp=
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
```
## Exceptions
```cpp=
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
}
```
## C++ standard library (libc)
### <algorithm>
```cpp=
#include <algorithm>
```
| Function | Description |
| -------- |:------------ |
| sort(v.begin(), v.end()) | Sorts the elements in the range \[first, last\) into ascending order. |
| upper_bound(v.begin(), v.end(), val) | Returns an iterator pointing to the first element in the range \[first, last\) which compares greater than val. |
| lower_bound(v.begin(), v.end(), val) | Returns an iterator pointing to the first element in the range \[first,last\) which does not compare less than val. |
| | |
ref:
[https://www.cplusplus.com/reference/clibrary/](https://www.cplusplus.com/reference/clibrary/)
ref:
[https://www.csie.ntu.edu.tw/~b98902112/cpp_and_algo/cpp/basic_structure.html](https://www.csie.ntu.edu.tw/~b98902112/cpp_and_algo/cpp/basic_structure.html)
[W3schools](https://www.w3schools.com/cpp/)