# C++

### Getting Started <a href="#getting-started" id="getting-started"></a>

#### hello.cpp <a href="#hello-cpp" id="hello-cpp"></a>

```cpp
#include <iostream>

int main() {
    std::cout << "Hello Vietelligent\n";
    return 0;
}
```

Compiling and running

```shell
$ g++ hello.cpp -o hello
$ ./hello
Hello Vietelligent
```

#### Variables <a href="#variables" id="variables"></a>

```cpp
int number = 5;       // Integer
float f = 0.95;       // Floating number
double PI = 3.14159;  // Floating number
char yes = 'Y';       // Character
std::string s = "ME"; // String (text)
bool isRight = true;  // Boolean

// Constants
const float RATE = 0.8;
```

***

```cpp
int age {25};         // Since C++11
std::cout << age;     // Print 25
```

#### Primitive Data Types <a href="#primitive-data-types" id="primitive-data-types"></a>

| Data Type | Size         | Range            |
| --------- | ------------ | ---------------- |
| `int`     | 4 bytes      | -231 to 231-1    |
| `float`   | 4 bytes      | *N/A*            |
| `double`  | 8 bytes      | *N/A*            |
| `char`    | 1 byte       | -128 to 127      |
| `bool`    | 1 byte       | true / false     |
| `void`    | *N/A*        | *N/A*            |
| `wchar_t` | 2 or 4 bytes | 1 wide character |

#### User Input <a href="#user-input" id="user-input"></a>

```cpp
int num;

std::cout << "Type a number: ";
std::cin >> num;

std::cout << "You entered " << num;
```

#### Swap <a href="#swap" id="swap"></a>

```cpp
int a = 5, b = 10;
std::swap(a, b);

// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;
```

#### Comments <a href="#comments" id="comments"></a>

```cpp
// A single one line comment in C++

/* This is a multiple line comment
   in C++ */
```

#### If statement <a href="#if-statement" id="if-statement"></a>

```cpp
if (a == 10) {
    // do something
}
```

See: Conditionals

#### Loops <a href="#loops" id="loops"></a>

```cpp
for (int i = 0; i < 10; i++) {
    std::cout << i << "\n";
}
```

See: [Loops](#c-loops)

#### Functions <a href="#functions" id="functions"></a>

```cpp
#include <iostream>
 
void hello(); // Declaring
 
int main() {  // main function
    hello();    // Calling
}
 
void hello() { // Defining
    std::cout << "Hello Vietelligent!\n";
}
```

See: [Functions](#c-functions)

#### References <a href="#references" id="references"></a>

```cpp
int i = 1;
int& ri = i; // ri is a reference to i

ri = 2; // i is now changed to 2
std::cout << "i=" << i;

i = 3;   // i is now changed to 3
std::cout << "ri=" << ri;
```

`ri` and `i` refer to the same memory location.

#### Namespaces <a href="#namespaces" id="namespaces"></a>

```cpp
#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
    std::cout << ns1::val();
}
```

***

```cpp
#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
    cout << val(); 
}
```

Namespaces allow global identifiers under a name

### C++ Arrays <a href="#c-arrays" id="c-arrays"></a>

#### Declaration <a href="#declaration" id="declaration"></a>

```cpp
std::array<int, 3> marks; // Definition
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;

// Define and initialize
std::array<int, 3> = {92, 97, 98};

// With empty members
std::array<int, 3> marks = {92, 97};
std::cout << marks[2]; // Outputs: 0
```

#### Manipulation <a href="#manipulation" id="manipulation"></a>

```cpp
┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92  | 97  | 98  | 99  | 98  | 94  |
└─────┴─────┴─────┴─────┴─────┴─────┘
   0     1     2     3     4     5
```

***

```cpp
std::array<int, 6> marks = {92, 97, 98, 99, 98, 94};

// Print first element
std::cout << marks[0];

// Change 2th element to 99
marks[1] = 99;

// Take input from the user
std::cin >> marks[2];
```

#### Displaying <a href="#displaying" id="displaying"></a>

```cpp
char ref[5] = {'R', 'e', 'f'};

// Range based for loop
for (const int &n : ref) {
    std::cout << std::string(1, n);
}

// Traditional for loop
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}
```

#### Multidimensional <a href="#multidimensional" id="multidimensional"></a>

```cpp
     j0   j1   j2   j3   j4   j5
   ┌────┬────┬────┬────┬────┬────┐
i0 | 1  | 2  | 3  | 4  | 5  | 6  |
   ├────┼────┼────┼────┼────┼────┤
i1 | 6  | 5  | 4  | 3  | 2  | 1  |
   └────┴────┴────┴────┴────┴────┘
```

***

```cpp
int x[2][6] = {
    {1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
        std::cout << x[i][j] << " ";
    }
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 
```

### C++ Conditionals <a href="#c-conditionals" id="c-conditionals"></a>

#### If Clause <a href="#if-clause" id="if-clause"></a>

```cpp
if (a == 10) {
    // do something
}
```

***

```cpp
int number = 16;

if (number % 2 == 0)
{
    std::cout << "even";
}
else
{
    std::cout << "odd";
}

// Outputs: even
```

#### Else if Statement <a href="#else-if-statement" id="else-if-statement"></a>

```cpp
int score = 99;
if (score == 100) {
    std::cout << "Superb";
}
else if (score >= 90) {
    std::cout << "Excellent";
}
else if (score >= 80) {
    std::cout << "Very Good";
}
else if (score >= 70) {
    std::cout << "Good";
}
else if (score >= 60)
    std::cout << "OK";
else
    std::cout << "What?";
```

#### Operators <a href="#operators" id="operators"></a>

**Relational Operators**

| `a == b` | a is equal to b              |
| -------- | ---------------------------- |
| `a != b` | a is NOT equal to b          |
| `a < b`  | a is less than b             |
| `a > b`  | a is greater b               |
| `a <= b` | a is less than or equal to b |
| `a >= b` | a is greater or equal to b   |

**Assignment Operators**

| `a += b` | *Aka* a = a + b  |
| -------- | ---------------- |
| `a -= b` | *Aka* a = a - b  |
| `a *= b` | *Aka* a = a \* b |
| `a /= b` | *Aka* a = a / b  |
| `a %= b` | *Aka* a = a % b  |

**Logical Operators**

| `exp1 && exp2`   | Both are true *(AND)*  |
| ---------------- | ---------------------- |
| `exp1 \|\| exp2` | Either is true *(OR)*  |
| `!exp`           | `exp` is false *(NOT)* |

**Bitwise Operators**

| `a & b`  | Binary AND              |
| -------- | ----------------------- |
| `a \| b` | Binary OR               |
| `a ^ b`  | Binary XOR              |
| `~ a`    | Binary One's Complement |
| `a << b` | Binary Shift Left       |
| `a >> b` | Binary Shift Right      |

#### Ternary Operator <a href="#ternary-operator" id="ternary-operator"></a>

```
           ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
           └───── False ─────┘
```

***

```cpp
int x = 3, y = 5, max;
max = (x > y) ? x : y;

// Outputs: 5
std::cout << max << std::endl;
```

***

```cpp
int x = 3, y = 5, max;
if (x > y) {
    max = x;
} else {
    max = y;
}
// Outputs: 5
std::cout << max << std::endl;
```

#### Switch Statement <a href="#switch-statement" id="switch-statement"></a>

```cpp
int num = 2;
switch (num) {
    case 0:
        std::cout << "Zero";
        break;
    case 1:
        std::cout << "One";
        break;
    case 2:
        std::cout << "Two";
        break;
    case 3:
        std::cout << "Three";
        break;
    default:
        std::cout << "What?";
        break;
}
```

### C++ Loops <a href="#c-loops" id="c-loops"></a>

#### While <a href="#while" id="while"></a>

```cpp
int i = 0;
while (i < 6) {
    std::cout << i++;
}

// Outputs: 012345
```

#### Do-while <a href="#do-while" id="do-while"></a>

```cpp
int i = 1;
do {
    std::cout << i++;
} while (i <= 5);

// Outputs: 12345
```

#### Continue statements <a href="#continue-statements" id="continue-statements"></a>

```cpp
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    std::cout << i;
} // Outputs: 13579
```

#### Infinite loop <a href="#infinite-loop" id="infinite-loop"></a>

```cpp
while (true) { // true or 1
    std::cout << "infinite loop";
}
```

```cpp
for (;;) {
    std::cout << "infinite loop";
}
```

```cpp
for(int i = 1; i > 0; i++) {
    std::cout << "infinite loop";
}
```

#### for\_each (Since C++11) <a href="#for-each-since-c-11" id="for-each-since-c-11"></a>

```cpp
#include <iostream>

int main()
{
    auto print = [](int num) { std::cout << num << std::endl; };

    std::array<int, 4> arr = {1, 2, 3, 4};
    std::for_each(arr.begin(), arr.end(), print);
    return 0;
}
```

#### Range-based (Since C++11) <a href="#range-based-since-c-11" id="range-based-since-c-11"></a>

```cpp
for (int n : {1, 2, 3, 4, 5}) {
    std::cout << n << " ";
}
// Outputs: 1 2 3 4 5
```

***

```cpp
std::string hello = "Vietelligent.ME";
for (char c: hello)
{
    std::cout << c << " ";
}
// Outputs: V i e t e l l i g e n t . M E 
```

#### Break statements <a href="#break-statements" id="break-statements"></a>

```cpp
int password, times = 0;
while (password != 1234) {
    if (times++ >= 3) {
        std::cout << "Locked!\n";
        break;
    }
    std::cout << "Password: ";
    std::cin >> password; // input
}
```

#### Several variations <a href="#several-variations" id="several-variations"></a>

```cpp
for (int i = 0, j = 2; i < 3; i++, j--){
    std::cout << "i=" << i << ",";
    std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;
```

### C++ Functions <a href="#c-functions" id="c-functions"></a>

#### Arguments & Returns <a href="#arguments-returns" id="arguments-returns"></a>

```cpp
#include <iostream>

int add(int a, int b) {
    return a + b;  
}

int main() {
    std::cout << add(10, 20); 
}
```

`add` is a function taking 2 ints and returning int

#### Overloading <a href="#overloading" id="overloading"></a>

```cpp
void fun(string a, string b) {
    std::cout << a + " " + b;
}
void fun(string a) {
    std::cout << a;
}
void fun(int a) {
    std::cout << a;
}
```

#### Built-in Functions <a href="#built-in-functions" id="built-in-functions"></a>

```cpp
#include <iostream>
#include <cmath> // import library
 
int main() {
    // sqrt() is from cmath
    std::cout << sqrt(9);
}
```

### C++ Classes & Objects <a href="#c-classes-objects" id="c-classes-objects"></a>

#### Defining a Class <a href="#defining-a-class" id="defining-a-class"></a>

```cpp
class MyClass {
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

```

#### Creating an Object <a href="#creating-an-object" id="creating-an-object"></a>

```cpp
MyClass myObj;  // Create an object of MyClass

myObj.myNum = 15;          // Set the value of myNum to 15
myObj.myString = "Hello";  // Set the value of myString to "Hello"

cout << myObj.myNum << endl;         // Output 15
cout << myObj.myString << endl;      // Output "Hello"

```

#### Constructors <a href="#constructors" id="constructors"></a>

```cpp
class MyClass {
  public:
    int myNum;
    string myString;
    MyClass() {  // Constructor
      myNum = 0;
      myString = "";
    }
};

MyClass myObj;  // Create an object of MyClass

cout << myObj.myNum << endl;         // Output 0
cout << myObj.myString << endl;      // Output ""

```

#### Destructors <a href="#destructors" id="destructors"></a>

```cpp
class MyClass {
  public:
    int myNum;
    string myString;
    MyClass() {  // Constructor
      myNum = 0;
      myString = "";
    }
    ~MyClass() {  // Destructor
      cout << "Object destroyed." << endl;
    }
};

MyClass myObj;  // Create an object of MyClass

// Code here...

// Object is destroyed automatically when the program exits the scope


```

#### Class Methods <a href="#class-methods" id="class-methods"></a>

```cpp
class MyClass {
  public:
    int myNum;
    string myString;
    void myMethod() {  // Method/function defined inside the class
      cout << "Hello World!" << endl;
    }
};

MyClass myObj;  // Create an object of MyClass
myObj.myMethod();  // Call the method
```

#### Access Modifiers <a href="#access-modifiers" id="access-modifiers"></a>

```cpp
class MyClass {
  public:     // Public access specifier
    int x;    // Public attribute
  private:    // Private access specifier
    int y;    // Private attribute
  protected:  // Protected access specifier
    int z;    // Protected attribute
};

MyClass myObj;
myObj.x = 25;  // Allowed (public)
myObj.y = 50;  // Not allowed (private)
myObj.z = 75;  // Not allowed (protected)

```

#### Getters and Setters <a href="#getters-and-setters" id="getters-and-setters"></a>

```cpp
class MyClass {
  private:
    int myNum;
  public:
    void setMyNum(int num) {  // Setter
      myNum = num;
    }
    int getMyNum() {  // Getter
      return myNum;
    }
};

MyClass myObj;
myObj.setMyNum(15);  // Set the value of myNum to 15
cout << myObj.getMyNum() << endl;  // Output 15

```

#### Inheritance <a href="#inheritance" id="inheritance"></a>

```cpp
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut!" << endl;
    }
};

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

Car myCar;
myCar.honk();  // Output "Tuut, tuut!"
cout << myCar.brand + " " + myCar.model << endl;  // Output "Ford Mustang"
```

### C++ Preprocessor <a href="#c-preprocessor" id="c-preprocessor"></a>

#### Preprocessor <a href="#preprocessor" id="preprocessor"></a>

* [if](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [elif](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [else](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [endif](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [ifdef](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [ifndef](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [define](https://en.cppreference.com/w/cpp/preprocessor/replace)
* [undef](https://en.cppreference.com/w/cpp/preprocessor/replace)
* [include](https://en.cppreference.com/w/cpp/preprocessor/include)
* [line](https://en.cppreference.com/w/cpp/preprocessor/line)
* [error](https://en.cppreference.com/w/cpp/preprocessor/error)
* [pragma](https://en.cppreference.com/w/cpp/preprocessor/impl)
* [defined](https://en.cppreference.com/w/cpp/preprocessor/conditional)
* [\_\_has\_include](https://en.cppreference.com/w/cpp/feature_test)
* [\_\_has\_cpp\_attribute](https://en.cppreference.com/w/cpp/feature_test)
* [export](https://en.cppreference.com/w/cpp/keyword/export)
* [import](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/import\&action=edit\&redlink=1)
* [module](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/module\&action=edit\&redlink=1)

#### Includes <a href="#includes" id="includes"></a>

```cpp
#include "iostream"
#include <iostream>
```

#### Defines <a href="#defines" id="defines"></a>

```cpp
#define FOO
#define FOO "hello"

#undef FOO
```

#### If <a href="#if" id="if"></a>

```cpp
#ifdef DEBUG
  console.log('hi');
#elif defined VERBOSE
  ...
#else
  ...
#endif
```

#### Error <a href="#error" id="error"></a>

```cpp
#if VERSION == 2.0
  #error Unsupported
  #warning Not really supported
#endif
```

#### Macro <a href="#macro" id="macro"></a>

```cpp
#define DEG(x) ((x) * 57.29)
```

#### Token concat <a href="#token-concat" id="token-concat"></a>

```cpp
#define DST(name) name##_s name##_t
DST(object);   #=> object_s object_t;
```

#### Stringification <a href="#stringification" id="stringification"></a>

```cpp
#define STR(name) #name
char * a = STR(object);   #=> char * a = "object";
```

#### file and line <a href="#file-and-line" id="file-and-line"></a>

```cpp
#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")
```

### Miscellaneous <a href="#miscellaneous" id="miscellaneous"></a>

#### Escape Sequences <a href="#escape-sequences" id="escape-sequences"></a>

| `\b` | Backspace             |
| ---- | --------------------- |
| `\f` | Form feed             |
| `\n` | Newline               |
| `\r` | Return                |
| `\t` | Horizontal tab        |
| `\v` | Vertical tab          |
| `\\` | Backslash             |
| `\'` | Single quotation mark |
| `\"` | Double quotation mark |
| `\?` | Question mark         |
| `\0` | Null Character        |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nvb99.gitbook.io/me/cheat-sheet/programming-language/c++.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
