Add content to C++ roadmap

pull/3988/head
Kamran Ahmed 2 years ago
parent 36eed57ec2
commit 9f5d1aef74
  1. 20
      src/data/roadmaps/cpp/content/100-introduction/102-c-vs-cpp.md
  2. 20
      src/data/roadmaps/cpp/content/100-introduction/index.md
  3. 14
      src/data/roadmaps/cpp/content/101-setting-up/100-installing.md
  4. 6
      src/data/roadmaps/cpp/content/101-setting-up/101-code-editors.md
  5. 8
      src/data/roadmaps/cpp/content/101-setting-up/102-first-program.md
  6. 14
      src/data/roadmaps/cpp/content/101-setting-up/index.md
  7. 6
      src/data/roadmaps/cpp/content/102-basic-operations/101-logical-operators.md
  8. 12
      src/data/roadmaps/cpp/content/102-basic-operations/103-bitwise.md
  9. 109
      src/data/roadmaps/cpp/content/102-basic-operations/index.md
  10. 8
      src/data/roadmaps/cpp/content/103-functions/100-lambda.md
  11. 8
      src/data/roadmaps/cpp/content/103-functions/101-operators.md
  12. 4
      src/data/roadmaps/cpp/content/103-functions/index.md
  13. 8
      src/data/roadmaps/cpp/content/104-data-types/101-dynamic-typing/100-rtti.md
  14. 4
      src/data/roadmaps/cpp/content/104-data-types/101-dynamic-typing/index.md
  15. 24
      src/data/roadmaps/cpp/content/104-data-types/index.md
  16. 6
      src/data/roadmaps/cpp/content/105-pointers-and-references/100-references.md
  17. 8
      src/data/roadmaps/cpp/content/105-pointers-and-references/101-memory-model/100-object-lifetime.md
  18. 6
      src/data/roadmaps/cpp/content/105-pointers-and-references/raw-pointers/100-new-delete-operators.md
  19. 2
      src/data/roadmaps/cpp/content/105-pointers-and-references/smart-pointers/101-shared-ptr.md
  20. 14
      src/data/roadmaps/cpp/content/106-structuring-codebase/100-scope/100-namespaces.md
  21. 8
      src/data/roadmaps/cpp/content/106-structuring-codebase/100-scope/index.md
  22. 6
      src/data/roadmaps/cpp/content/106-structuring-codebase/101-code-splitting/100-forward-declaration.md
  23. 6
      src/data/roadmaps/cpp/content/106-structuring-codebase/101-code-splitting/index.md
  24. 10
      src/data/roadmaps/cpp/content/107-structures-and-classes/100-rule-of-zero-five-three.md
  25. 4
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/100-static-polymorphism/index.md
  26. 2
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/100-static-polymorphism/overloading-functions.md
  27. 2
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/101-dynamic-polymorphism/index.md
  28. 2
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/101-dynamic-polymorphism/virtual-methods.md
  29. 2
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/101-dynamic-polymorphism/virtual-tables.md
  30. 8
      src/data/roadmaps/cpp/content/107-structures-and-classes/101-oop/index.md
  31. 6
      src/data/roadmaps/cpp/content/107-structures-and-classes/102-multiple-inheritance/index.md
  32. 16
      src/data/roadmaps/cpp/content/108-exception-handling/100-exceptions/100-access-violations.md
  33. 4
      src/data/roadmaps/cpp/content/108-exception-handling/101-exit-codes.md
  34. 10
      src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/100-static-cast.md
  35. 2
      src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/101-const-cast.md
  36. 10
      src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/index.md
  37. 8
      src/data/roadmaps/cpp/content/109-language-concepts/102-undefined-behavior.md
  38. 2
      src/data/roadmaps/cpp/content/109-language-concepts/103-adl.md
  39. 6
      src/data/roadmaps/cpp/content/109-language-concepts/105-macros.md
  40. 16
      src/data/roadmaps/cpp/content/109-language-concepts/index.md
  41. 10
      src/data/roadmaps/cpp/content/110-stl/100-iterators.md
  42. 12
      src/data/roadmaps/cpp/content/110-stl/102-algorithms.md
  43. 8
      src/data/roadmaps/cpp/content/110-stl/103-date-time.md
  44. 6
      src/data/roadmaps/cpp/content/110-stl/104-multithreading.md
  45. 8
      src/data/roadmaps/cpp/content/110-stl/105-ccontainers.md
  46. 8
      src/data/roadmaps/cpp/content/110-stl/index.md
  47. 8
      src/data/roadmaps/cpp/content/111-templates/100-variadic-templates.md
  48. 4
      src/data/roadmaps/cpp/content/111-templates/101-template-specialization/100-full.md
  49. 8
      src/data/roadmaps/cpp/content/111-templates/101-template-specialization/index.md
  50. 4
      src/data/roadmaps/cpp/content/111-templates/102-type-traits.md
  51. 2
      src/data/roadmaps/cpp/content/111-templates/103-finae.md
  52. 6
      src/data/roadmaps/cpp/content/111-templates/index.md
  53. 2
      src/data/roadmaps/cpp/content/112-idioms/100-raii.md
  54. 2
      src/data/roadmaps/cpp/content/112-idioms/101-pimpl.md
  55. 4
      src/data/roadmaps/cpp/content/112-idioms/104-erase-remove.md
  56. 12
      src/data/roadmaps/cpp/content/112-idioms/105-copy-swap.md
  57. 2
      src/data/roadmaps/cpp/content/113-standards/101-cpp17.md
  58. 8
      src/data/roadmaps/cpp/content/113-standards/102-cpp20.md
  59. 10
      src/data/roadmaps/cpp/content/113-standards/103-newest.md
  60. 10
      src/data/roadmaps/cpp/content/113-standards/index.md
  61. 10
      src/data/roadmaps/cpp/content/114-debuggers/100-debugger-messages.md
  62. 6
      src/data/roadmaps/cpp/content/114-debuggers/101-debugger-symbols.md
  63. 22
      src/data/roadmaps/cpp/content/114-debuggers/102-win-dbg.md
  64. 6
      src/data/roadmaps/cpp/content/114-debuggers/103-gdb.md
  65. 12
      src/data/roadmaps/cpp/content/114-debuggers/index.md
  66. 8
      src/data/roadmaps/cpp/content/115-compilers/100-stages.md
  67. 90
      src/data/roadmaps/cpp/content/115-compilers/101-features.md
  68. 14
      src/data/roadmaps/cpp/content/115-compilers/index.md
  69. 10
      src/data/roadmaps/cpp/content/116-build-systems/100-cmake.md
  70. 12
      src/data/roadmaps/cpp/content/116-build-systems/101-makefile.md
  71. 10
      src/data/roadmaps/cpp/content/116-build-systems/index.md
  72. 10
      src/data/roadmaps/cpp/content/117-package-managers/100-vcpkg.md
  73. 14
      src/data/roadmaps/cpp/content/117-package-managers/101-spack.md
  74. 12
      src/data/roadmaps/cpp/content/117-package-managers/102-conan.md
  75. 14
      src/data/roadmaps/cpp/content/117-package-managers/103-nuget.md
  76. 12
      src/data/roadmaps/cpp/content/117-package-managers/index.md
  77. 8
      src/data/roadmaps/cpp/content/118-working-with-libs/100-inclusion.md
  78. 6
      src/data/roadmaps/cpp/content/118-working-with-libs/101-licensing.md
  79. 22
      src/data/roadmaps/cpp/content/frameworks/100-gtest.md
  80. 4
      src/data/roadmaps/cpp/content/frameworks/101-qt.md
  81. 8
      src/data/roadmaps/cpp/content/frameworks/102-catch2.md
  82. 12
      src/data/roadmaps/cpp/content/frameworks/103-orbit-profiler.md
  83. 6
      src/data/roadmaps/cpp/content/frameworks/104-pytorch-cpp.md
  84. 4
      src/data/roadmaps/cpp/content/libraries/100-boost.md
  85. 4
      src/data/roadmaps/cpp/content/libraries/102-poco.md
  86. 8
      src/data/roadmaps/cpp/content/libraries/103-protobuf.md
  87. 6
      src/data/roadmaps/cpp/content/libraries/104-grpc.md
  88. 2
      src/data/roadmaps/cpp/content/libraries/106-pybind11.md
  89. 6
      src/data/roadmaps/cpp/content/libraries/107-spdlog.md
  90. 16
      src/data/roadmaps/cpp/content/libraries/108-opencl.md
  91. 8
      src/data/roadmaps/cpp/content/libraries/109-fmt.md
  92. 12
      src/data/roadmaps/cpp/content/libraries/110-ranges-v3.md

@ -1,9 +1,9 @@
# C vs C++ # C vs C++
C and C++ are two popular programming languages with some similarities, but they also have key differences. C++ is an extension of the C programming language, with added features such as object-oriented programming, classes, and exception handling. Although both languages are used for similar tasks, they have their own syntax and semantics, which makes them distinct from each other. C and C++ are two popular programming languages with some similarities, but they also have key differences. C++ is an extension of the C programming language, with added features such as object-oriented programming, classes, and exception handling. Although both languages are used for similar tasks, they have their own syntax and semantics, which makes them distinct from each other.
### Syntax and Semantics ## Syntax and Semantics
#### C ### C
- C is a procedural programming language. - C is a procedural programming language.
- Focuses on functions and structured programming. - Focuses on functions and structured programming.
- Does not support objects or classes. - Does not support objects or classes.
@ -22,7 +22,7 @@ int main() {
} }
``` ```
#### C++ ### C++
- C++ is both procedural and object-oriented. - C++ is both procedural and object-oriented.
- Supports both functions and classes. - Supports both functions and classes.
- Incorporates different programming paradigms. - Incorporates different programming paradigms.
@ -45,27 +45,27 @@ int main() {
} }
``` ```
### Code Reusability and Modularity ## Code Reusability and Modularity
#### C ### C
- Code reusability is achieved through functions and modular programming. - Code reusability is achieved through functions and modular programming.
- High cohesion and low coupling are achieved via structured design. - High cohesion and low coupling are achieved via structured design.
- Function libraries can be created and included through headers. - Function libraries can be created and included through headers.
#### C++ ### C++
- Offers better code reusability with classes, inheritance, and polymorphism. - Offers better code reusability with classes, inheritance, and polymorphism.
- Code modularity is enhanced through namespaces and well-designed object-oriented hierarchy. - Code modularity is enhanced through namespaces and well-designed object-oriented hierarchy.
### Error Handling ## Error Handling
#### C ### C
- Error handling in C is done primarily through return codes. - Error handling in C is done primarily through return codes.
- Lacks support for exceptions or any built-in error handling mechanism. - Lacks support for exceptions or any built-in error handling mechanism.
#### C++ ### C++
- Offers exception handling, which can be used to handle errors that may occur during program execution. - Offers exception handling, which can be used to handle errors that may occur during program execution.
- Enables catching and handling exceptions with `try`, `catch`, and `throw` keywords, providing more control over error handling. - Enables catching and handling exceptions with `try`, `catch`, and `throw` keywords, providing more control over error handling.
### Conclusion ## Conclusion
Both C and C++ are powerful languages with unique features and capabilities. While C is simpler and focuses on procedural programming, C++ offers the versatility of using different programming paradigms and improved code organization. Understanding the differences between these two languages can help you decide which one is more suitable for your specific needs and programming style. Both C and C++ are powerful languages with unique features and capabilities. While C is simpler and focuses on procedural programming, C++ offers the versatility of using different programming paradigms and improved code organization. Understanding the differences between these two languages can help you decide which one is more suitable for your specific needs and programming style.

@ -6,7 +6,7 @@ C++ is a general-purpose, high-performance programming language. It was develope
Here are some basic components and concepts in C++ programming: Here are some basic components and concepts in C++ programming:
### Including Libraries ## Including Libraries
In C++, we use the `#include` directive to include libraries or header files into our program. For example, to include the standard input/output library, we write: In C++, we use the `#include` directive to include libraries or header files into our program. For example, to include the standard input/output library, we write:
@ -14,7 +14,7 @@ In C++, we use the `#include` directive to include libraries or header files int
#include <iostream> #include <iostream>
``` ```
### Main Function ## Main Function
The entry point of a C++ program is the `main` function. Every C++ program must have a `main` function: The entry point of a C++ program is the `main` function. Every C++ program must have a `main` function:
@ -25,7 +25,7 @@ int main() {
} }
``` ```
### Input/Output ## Input/Output
To perform input and output operations in C++, we can use the built-in objects `std::cin` for input and `std::cout` for output, available in the `iostream` library. Here's an example of reading an integer and printing its value: To perform input and output operations in C++, we can use the built-in objects `std::cin` for input and `std::cout` for output, available in the `iostream` library. Here's an example of reading an integer and printing its value:
@ -41,7 +41,7 @@ int main() {
} }
``` ```
### Variables and Data Types ## Variables and Data Types
C++ has several basic data types for representing integer, floating-point, and character values: C++ has several basic data types for representing integer, floating-point, and character values:
@ -59,11 +59,11 @@ double z;
char c; char c;
``` ```
### Control Structures ## Control Structures
C++ provides control structures for conditional execution and iteration, such as `if`, `else`, `while`, `for`, and `switch` statements. C++ provides control structures for conditional execution and iteration, such as `if`, `else`, `while`, `for`, and `switch` statements.
#### If-Else Statement ### If-Else Statement
```cpp ```cpp
if (condition) { if (condition) {
// Code to execute if the condition is true // Code to execute if the condition is true
@ -72,21 +72,21 @@ if (condition) {
} }
``` ```
#### While Loop ### While Loop
```cpp ```cpp
while (condition) { while (condition) {
// Code to execute while the condition is true // Code to execute while the condition is true
} }
``` ```
#### For Loop ### For Loop
```cpp ```cpp
for (initialization; condition; update) { for (initialization; condition; update) {
// Code to execute while the condition is true // Code to execute while the condition is true
} }
``` ```
#### Switch Statement ### Switch Statement
```cpp ```cpp
switch (variable) { switch (variable) {
case value1: case value1:
@ -101,7 +101,7 @@ switch (variable) {
} }
``` ```
### Functions ## Functions
Functions are reusable blocks of code that can be called with arguments to perform a specific task. Functions are defined with a return type, a name, a parameter list, and a body. Functions are reusable blocks of code that can be called with arguments to perform a specific task. Functions are defined with a return type, a name, a parameter list, and a body.

@ -1,16 +1,16 @@
# Installing C++ # Installing C++
Before you can start programming in C++, you will need to have a compiler installed on your system. A compiler is a program that converts the C++ code you write into an executable file that your computer can run. There are several popular C++ compilers to choose from, depending on your operating system and preference. Before you can start programming in C++, you will need to have a compiler installed on your system. A compiler is a program that converts the C++ code you write into an executable file that your computer can run. There are several popular C++ compilers to choose from, depending on your operating system and preference.
#### Windows ### Windows
For Windows, one popular option is to install the [Microsoft Visual Studio IDE](https://visualstudio.microsoft.com/vs/), which includes the Microsoft Visual C++ compiler. For Windows, one popular option is to install the [Microsoft Visual Studio IDE](https://visualstudio.microsoft.com/vs/), which includes the Microsoft Visual C++ compiler.
Alternatively, you can also install the [MinGW-w64](https://mingw-w64.org/doku.php) compiler, which is a Windows port of the GNU Compiler Collection (GCC). To install MinGW-w64, follow these steps: Alternatively, you can also install the [MinGW-w64](https://mingw-w64.org/doku.php) compiler, which is a Windows port of the GNU Compiler Collection (GCC). To install MinGW-w64, follow these steps:
1. Download the installer from [here](https://sourceforge.net/projects/mingw-w64/files/). - Download the installer from [here](https://sourceforge.net/projects/mingw-w64/files/).
2. Run the installer and select your desired architecture, version, and install location. - Run the installer and select your desired architecture, version, and install location.
3. Add the `bin` folder inside the installation directory to your system's `PATH` environment variable. - Add the `bin` folder inside the installation directory to your system's `PATH` environment variable.
#### macOS ### macOS
For macOS, you can install the Apple LLVM `clang` compiler which is part of the Xcode Command Line Tools. To do this, open a terminal and enter: For macOS, you can install the Apple LLVM `clang` compiler which is part of the Xcode Command Line Tools. To do this, open a terminal and enter:
``` ```
@ -19,7 +19,7 @@ xcode-select --install
This will prompt a dialog to install the Command Line Tools, which includes the `clang` compiler. This will prompt a dialog to install the Command Line Tools, which includes the `clang` compiler.
#### Linux ### Linux
On Linux, you can install the GNU Compiler Collection (GCC) through your distribution's package manager. Here are some examples for popular Linux distributions: On Linux, you can install the GNU Compiler Collection (GCC) through your distribution's package manager. Here are some examples for popular Linux distributions:
- Ubuntu, Debian, and derivatives: - Ubuntu, Debian, and derivatives:
@ -37,7 +37,7 @@ sudo dnf install gcc-c++ make
sudo pacman -S gcc make sudo pacman -S gcc make
``` ```
#### Checking the Installation ### Checking the Installation
To confirm that the compiler is installed and available on your system, open a terminal/command prompt, and enter the following command: To confirm that the compiler is installed and available on your system, open a terminal/command prompt, and enter the following command:
``` ```

@ -2,11 +2,11 @@
Code editors are programs specifically designed for editing, managing and writing source code. They offer a wide range of features that make the development process easier and faster. Here's a brief introduction to some of the most popular code editors for C++: Code editors are programs specifically designed for editing, managing and writing source code. They offer a wide range of features that make the development process easier and faster. Here's a brief introduction to some of the most popular code editors for C++:
1. **Visual Studio Code (VSCode)**: Visual Studio Code is a popular, free, open-source, and lightweight code editor developed by Microsoft. It has built-in support for C++, along with an extensive library of extensions and plugins. - **Visual Studio Code (VSCode)**: Visual Studio Code is a popular, free, open-source, and lightweight code editor developed by Microsoft. It has built-in support for C++, along with an extensive library of extensions and plugins.
2. **Sublime Text**: Sublime Text is a cross-platform text editor that is quite popular among developers due to its speed and minimalist design. It supports C++ with the help of plugins and has a variety of themes and packages available for customization. - **Sublime Text**: Sublime Text is a cross-platform text editor that is quite popular among developers due to its speed and minimalist design. It supports C++ with the help of plugins and has a variety of themes and packages available for customization.
3. **CLion**: CLion is an Integrated Development Environment (IDE) developed by JetBrains specifically for C and C++ developers. It provides advanced features like code completion, refactoring support, debugging, and more. - **CLion**: CLion is an Integrated Development Environment (IDE) developed by JetBrains specifically for C and C++ developers. It provides advanced features like code completion, refactoring support, debugging, and more.
These are just a few examples, and there are many other code editors available, including Atom, Notepad++, and Geany. They all have their features and may suit different developers' needs. Finding the right code editor is often a matter of personal preference and workflow. These are just a few examples, and there are many other code editors available, including Atom, Notepad++, and Geany. They all have their features and may suit different developers' needs. Finding the right code editor is often a matter of personal preference and workflow.

@ -17,7 +17,7 @@ int main() {
Let's break down the different components of this program: Let's break down the different components of this program:
### Header Files & Preprocessor Directives ## Header Files & Preprocessor Directives
The first line of the program `#include <iostream>` is a [preprocessor directive](https://en.cppreference.com/w/cpp/preprocessor) that tells the compiler to include the header file `iostream`. Header files provide function and class declarations that we can use in our C++ programs. The first line of the program `#include <iostream>` is a [preprocessor directive](https://en.cppreference.com/w/cpp/preprocessor) that tells the compiler to include the header file `iostream`. Header files provide function and class declarations that we can use in our C++ programs.
@ -25,7 +25,7 @@ The first line of the program `#include <iostream>` is a [preprocessor directive
#include <iostream> #include <iostream>
``` ```
### `main()` Function ##`main()` Function
In C++, the `main()` function serves as the entry point of your program. The operating system runs your program by calling this `main()` function. It should be defined only once in your program and must return an integer. In C++, the `main()` function serves as the entry point of your program. The operating system runs your program by calling this `main()` function. It should be defined only once in your program and must return an integer.
@ -35,7 +35,7 @@ int main() {
} }
``` ```
### Output to the Console ## Output to the Console
To output text to the console, we use the `std::cout` object and the insertion operator `<<`. In the "Hello, World!" example, we used the following line to print "Hello, World!" to the console: To output text to the console, we use the `std::cout` object and the insertion operator `<<`. In the "Hello, World!" example, we used the following line to print "Hello, World!" to the console:
@ -47,7 +47,7 @@ std::cout << "Hello, World!" << std::endl;
- `"Hello, World!"`: The string literal to print - `"Hello, World!"`: The string literal to print
- `std::endl`: The "end line" manipulator that inserts a newline character and flushes the output buffer - `std::endl`: The "end line" manipulator that inserts a newline character and flushes the output buffer
### Return Statement ## Return Statement
Lastly, the `return 0;` statement informs the operating system that the program executed successfully. Returning any other integer value indicates that an error occurred: Lastly, the `return 0;` statement informs the operating system that the program executed successfully. Returning any other integer value indicates that an error occurred:

@ -26,10 +26,10 @@ After downloading and installing an IDE, you might need to configure it to use t
Once you have your IDE and compiler set up, you can create a new C++ project and start writing code. In general, follow these steps to create a new C++ project: Once you have your IDE and compiler set up, you can create a new C++ project and start writing code. In general, follow these steps to create a new C++ project:
1. Open the IDE and create a new project. - Open the IDE and create a new project.
2. Select the project type (C++ Application or Console Application). - Select the project type (C++ Application or Console Application).
3. Specify the project name and location. - Specify the project name and location.
4. Let the IDE generate the main.cpp and build files (such as Makefile or CMakeLists.txt) for you. - Let the IDE generate the main.cpp and build files (such as Makefile or CMakeLists.txt) for you.
## Example: Hello World in C++ ## Example: Hello World in C++
@ -50,8 +50,8 @@ Then, follow the IDE's instructions to build and run your program. You should se
Setting up C++ involves: Setting up C++ involves:
1. Installing a compiler (e.g. GCC, MinGW, or MSVC) - Installing a compiler (e.g. GCC, MinGW, or MSVC)
2. Configuring an IDE (e.g. Visual Studio, Eclipse, or Code::Blocks) - Configuring an IDE (e.g. Visual Studio, Eclipse, or Code::Blocks)
3. Creating a new C++ project and writing code - Creating a new C++ project and writing code
By following these steps, you'll be ready to start developing C++ applications! By following these steps, you'll be ready to start developing C++ applications!

@ -4,7 +4,7 @@ Logical operators are used to perform logical operations on the given expression
C++ provides the following logical operators: C++ provides the following logical operators:
1. **AND Operator (&&)** - **AND Operator (&&)**
The AND operator checks if both the operands/conditions are true, then the expression is true. If any one of the conditions is false, the whole expression will be false. The AND operator checks if both the operands/conditions are true, then the expression is true. If any one of the conditions is false, the whole expression will be false.
``` ```
(expression1 && expression2) (expression1 && expression2)
@ -16,7 +16,7 @@ C++ provides the following logical operators:
cout << "Both values are positive." << endl; cout << "Both values are positive." << endl;
} }
``` ```
2. **OR Operator (||)** - **OR Operator (||)**
The OR operator checks if either of the operands/conditions are true, then the expression is true. If both the conditions are false, it will be false. The OR operator checks if either of the operands/conditions are true, then the expression is true. If both the conditions are false, it will be false.
``` ```
(expression1 || expression2) (expression1 || expression2)
@ -29,7 +29,7 @@ C++ provides the following logical operators:
} }
``` ```
3. **NOT Operator (!)** - **NOT Operator (!)**
The NOT operator reverses the result of the condition/expression it is applied on. If the condition is true, the NOT operator will make it false and vice versa. The NOT operator reverses the result of the condition/expression it is applied on. If the condition is true, the NOT operator will make it false and vice versa.
``` ```
!(expression) !(expression)

@ -4,7 +4,7 @@ Bitwise operations are operations that directly manipulate the bits of a number.
Here is a quick summary of common bitwise operations in C++: Here is a quick summary of common bitwise operations in C++:
### 1. Bitwise AND (`&`) ## Bitwise AND (`&`)
The bitwise AND operation (`&`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in both input numbers are set (1); otherwise, the bit is unset (0). The bitwise AND operation (`&`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in both input numbers are set (1); otherwise, the bit is unset (0).
@ -14,7 +14,7 @@ Example:
int result = 5 & 3; // result will be 1 (0000 0101 & 0000 0011 = 0000 0001) int result = 5 & 3; // result will be 1 (0000 0101 & 0000 0011 = 0000 0001)
``` ```
### 2. Bitwise OR (`|`) ## Bitwise OR (`|`)
The bitwise OR operation (`|`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if at least one of the corresponding bits in either input number is set (1); otherwise, the bit is unset (0). The bitwise OR operation (`|`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if at least one of the corresponding bits in either input number is set (1); otherwise, the bit is unset (0).
@ -24,7 +24,7 @@ Example:
int result = 5 | 3; // result will be 7 (0000 0101 | 0000 0011 = 0000 0111) int result = 5 | 3; // result will be 7 (0000 0101 | 0000 0011 = 0000 0111)
``` ```
### 3. Bitwise XOR (`^`) ## Bitwise XOR (`^`)
The bitwise XOR (exclusive OR) operation (`^`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in the input numbers are different; otherwise, the bit is unset (0). The bitwise XOR (exclusive OR) operation (`^`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in the input numbers are different; otherwise, the bit is unset (0).
@ -34,7 +34,7 @@ Example:
int result = 5 ^ 3; // result will be 6 (0000 0101 ^ 0000 0011 = 0000 0110) int result = 5 ^ 3; // result will be 6 (0000 0101 ^ 0000 0011 = 0000 0110)
``` ```
### 4. Bitwise NOT (`~`) ## Bitwise NOT (`~`)
The bitwise NOT operation (`~`) is a unary operation that takes a single number, and returns a new number where each bit is inverted (1 becomes 0, and 0 becomes 1). The bitwise NOT operation (`~`) is a unary operation that takes a single number, and returns a new number where each bit is inverted (1 becomes 0, and 0 becomes 1).
@ -44,7 +44,7 @@ Example:
int result = ~5; // result will be -6 (1111 1010) int result = ~5; // result will be -6 (1111 1010)
``` ```
### 5. Bitwise Left Shift (`<<`) ## Bitwise Left Shift (`<<`)
The bitwise left shift operation (`<<`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the left by the specified shift amount. The vacated bits are filled with zeros. The bitwise left shift operation (`<<`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the left by the specified shift amount. The vacated bits are filled with zeros.
@ -54,7 +54,7 @@ Example:
int result = 5 << 1; // result will be 10 (0000 0101 << 1 = 0000 1010) int result = 5 << 1; // result will be 10 (0000 0101 << 1 = 0000 1010)
``` ```
### 6. Bitwise Right Shift (`>>`) ## Bitwise Right Shift (`>>`)
The bitwise right shift operation (`>>`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the right by the specified shift amount. The vacated bits are filled with zeros or sign bit depending on the input value being signed or unsigned. The bitwise right shift operation (`>>`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the right by the specified shift amount. The vacated bits are filled with zeros or sign bit depending on the input value being signed or unsigned.

@ -1 +1,108 @@
# Basic operations # Basic Operations in C++
Basic operations in C++ refer to the fundamental arithmetic, relational, and logical operations that can be performed using C++ programming language, which are essential for any kind of program or calculation in a real-world scenario.
Here's a summary of the basic operations in C++
## Arithmetic Operations
These operations are used for performing calculations in C++ and include the following:
- **Addition (+)**: Adds two numbers.
```cpp
int a = 5;
int b = 6;
int sum = a + b; // sum is 11
```
- **Subtraction (-)**: Subtracts one number from the other.
```cpp
int a = 10;
int b = 6;
int diff = a - b; // diff is 4
```
- **Multiplication (*)**: Multiplies two numbers.
```cpp
int a = 3;
int b = 4;
int product = a * b; // product is 12
```
- **Division (/)**: Divides one number by another, yields quotient.
```cpp
int a = 12;
int b = 4;
int quotient = a / b; // quotient is 3
```
- **Modulus (%)**: Divides one number by another, yields remainder.
```cpp
int a = 15;
int b = 4;
int remainder = a % b; // remainder is 3
```
## Relational Operators
These operations compare two values and return a boolean value (true/false) depending on the comparison. The relational operations are:
- **Equal to (==)**: Returns true if both operands are equal.
```cpp
5 == 5 // true
3 == 4 // false
```
- **Not equal to (!=)**: Returns true if operands are not equal.
```cpp
5 != 2 // true
1 != 1 // false
```
- **Greater than (>)**: Returns true if the first operand is greater than the second.
```cpp
5 > 3 // true
2 > 3 // false
```
- **Less than (<)**: Returns true if the first operand is less than the second.
```cpp
3 < 5 // true
6 < 5 // false
```
- **Greater than or equal to (>=)**: Returns true if the first operand is greater than or equal to the second.
```cpp
5 >= 5 // true
6 >= 2 // true
3 >= 4 // false
```
- **Less than or equal to (<=)**: Returns true if the first operand is less than or equal to the second.
```cpp
4 <= 4 // true
2 <= 3 // true
5 <= 4 // false
```
## Logical Operators
Logical operators are used for combining multiple conditions or boolean values.
- **AND (&&)**: Returns true if both operands are true.
```cpp
true && true // true
true && false // false
```
- **OR (||)**: Returns true if any one of the operands is true.
```cpp
true || false // true
false || false // false
```
- **NOT (!)**: Returns true if the operand is false and vice versa.
```cpp
!true // false
!false // true
```

@ -21,7 +21,7 @@ Here is a basic syntax of a lambda function in C++:
Here are a few examples to demonstrate the use of lambda functions in C++: Here are a few examples to demonstrate the use of lambda functions in C++:
1. Lambda function with no capture, parameters, or return type. - Lambda function with no capture, parameters, or return type.
```cpp ```cpp
auto printHello = []() { auto printHello = []() {
@ -30,7 +30,7 @@ auto printHello = []() {
printHello(); // Output: Hello, World! printHello(); // Output: Hello, World!
``` ```
2. Lambda function with parameters. - Lambda function with parameters.
```cpp ```cpp
auto add = [](int a, int b) { auto add = [](int a, int b) {
@ -39,7 +39,7 @@ auto add = [](int a, int b) {
int result = add(3, 4); // result = 7 int result = add(3, 4); // result = 7
``` ```
3. Lambda function with capture-by-value. - Lambda function with capture-by-value.
```cpp ```cpp
int multiplier = 3; int multiplier = 3;
@ -49,7 +49,7 @@ auto times = [multiplier](int a) {
int result = times(5); // result = 15 int result = times(5); // result = 15
``` ```
4. Lambda function with capture-by-reference. - Lambda function with capture-by-reference.
```cpp ```cpp
int expiresInDays = 45; int expiresInDays = 45;

@ -4,7 +4,7 @@ Operators in C++ are symbols that perform various operations on data, such as ar
Here is a list of the commonly used operator types in C++: Here is a list of the commonly used operator types in C++:
1. **Arithmetic Operators**: These are used for performing arithmetic operations like addition, subtraction, multiplication, and division. - **Arithmetic Operators**: These are used for performing arithmetic operations like addition, subtraction, multiplication, and division.
- `+`: addition - `+`: addition
```cpp ```cpp
@ -27,7 +27,7 @@ Here is a list of the commonly used operator types in C++:
int remainder = 7 % 3; // remainder will be 1 int remainder = 7 % 3; // remainder will be 1
``` ```
2. **Comparison (Relational) Operators**: These are used to compare two values and return true or false based on the comparison. - **Comparison (Relational) Operators**: These are used to compare two values and return true or false based on the comparison.
- `==`: equal to - `==`: equal to
```cpp ```cpp
@ -54,7 +54,7 @@ Here is a list of the commonly used operator types in C++:
bool isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual will be true bool isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual will be true
``` ```
3. **Logical Operators**: These operators are used to perform logical operations such as AND (&&), OR (||), and NOT (!) on boolean values. - **Logical Operators**: These operators are used to perform logical operations such as AND (&&), OR (||), and NOT (!) on boolean values.
- `&&`: logical AND - `&&`: logical AND
```cpp ```cpp
@ -69,7 +69,7 @@ Here is a list of the commonly used operator types in C++:
bool result = !false; // result will be true bool result = !false; // result will be true
``` ```
4. **Assignment Operators**: These are used to assign values to variables. - **Assignment Operators**: These are used to assign values to variables.
- `=`: simple assignment - `=`: simple assignment
```cpp ```cpp

@ -4,9 +4,9 @@ A **function** is a group of statements that perform a specific task, organized
There are mainly two types of functions in C++: There are mainly two types of functions in C++:
1. **Standard library functions**: Pre-defined functions available in the C++ standard library, such as `printf()`, `scanf()`, `sqrt()`, and many more. These functions are part of the standard library, so you need to include the appropriate header file to use them. - **Standard library functions**: Pre-defined functions available in the C++ standard library, such as `printf()`, `scanf()`, `sqrt()`, and many more. These functions are part of the standard library, so you need to include the appropriate header file to use them.
2. **User-defined functions**: Functions created by the programmer to perform a specific task. To create a user-defined function, you need to define the function and call it in your code. - **User-defined functions**: Functions created by the programmer to perform a specific task. To create a user-defined function, you need to define the function and call it in your code.
## Defining a Function ## Defining a Function

@ -4,10 +4,10 @@ Run-Time Type Identification (RTTI) is a feature in C++ that allows you to obtai
There are two main mechanisms for RTTI in C++: There are two main mechanisms for RTTI in C++:
1. `typeid` operator - `typeid` operator
2. `dynamic_cast` operator - `dynamic_cast` operator
### 1. typeid operator ## typeid operator
`typeid` is an operator that returns a reference to an object of type `std::type_info`, which contains information about the type of the object. The header file `<typeinfo>` should be included to use `typeid`. `typeid` is an operator that returns a reference to an object of type `std::type_info`, which contains information about the type of the object. The header file `<typeinfo>` should be included to use `typeid`.
@ -30,7 +30,7 @@ int main() {
} }
``` ```
### 2. dynamic_cast operator ## dynamic_cast operator
`dynamic_cast` is a type-casting operator that performs a runtime type check and safely downcasts a base pointer or reference to a derived pointer or reference. It returns null or throws a bad_cast exception (if casting references) when the casting fails. `dynamic_cast` is a type-casting operator that performs a runtime type check and safely downcasts a base pointer or reference to a derived pointer or reference. It returns null or throws a bad_cast exception (if casting references) when the casting fails.

@ -4,7 +4,7 @@ C++ is known as a statically-typed language, which means the data types of its v
Here is a brief overview of two ways to achieve dynamic typing in C++: Here is a brief overview of two ways to achieve dynamic typing in C++:
### 1. `void*` Pointers ## `void*` Pointers
A `void*` pointer is a generic pointer that can point to objects of any data type. They can be used to store a reference to any type of object without knowing the specific type of the object. A `void*` pointer is a generic pointer that can point to objects of any data type. They can be used to store a reference to any type of object without knowing the specific type of the object.
@ -32,7 +32,7 @@ int main() {
} }
``` ```
### 2. `std::any` (C++17) ## `std::any` (C++17)
C++17 introduced the `std::any` class which represents a generalized type-safe container for single values of any type. C++17 introduced the `std::any` class which represents a generalized type-safe container for single values of any type.

@ -4,7 +4,7 @@ In C++, data types are used to categorize different types of data that a program
## Fundamental Data Types ## Fundamental Data Types
### Integer (int) ## Integer (int)
Integers are whole numbers that can store both positive and negative values. The size of `int` depends on the system architecture (usually 4 bytes). Integers are whole numbers that can store both positive and negative values. The size of `int` depends on the system architecture (usually 4 bytes).
Example: Example:
@ -17,24 +17,24 @@ There are variants of `int` that can hold different ranges of numbers:
- long (`long int`): Larger range than `int`. - long (`long int`): Larger range than `int`.
- long long (`long long int`): Even larger range than `long int`. - long long (`long long int`): Even larger range than `long int`.
### Floating-Point (float, double) ## Floating-Point (float, double)
Floating-point types represent real numbers, i.e., numbers with a decimal point. There are two main floating-point types: Floating-point types represent real numbers, i.e., numbers with a decimal point. There are two main floating-point types:
1. **float**: Provides single-precision floating-point numbers. It typically occupies 4 bytes of memory. - **float**: Provides single-precision floating-point numbers. It typically occupies 4 bytes of memory.
Example: Example:
```cpp ```cpp
float pi = 3.14f; float pi = 3.14f;
``` ```
2. **double**: Provides double-precision floating-point numbers. It consumes more memory (usually 8 bytes) but has a higher precision than `float`. - **double**: Provides double-precision floating-point numbers. It consumes more memory (usually 8 bytes) but has a higher precision than `float`.
Example: Example:
```cpp ```cpp
double pi_high_precision = 3.1415926535; double pi_high_precision = 3.1415926535;
``` ```
### Character (char) ## Character (char)
Characters represent a single character, such as a letter, digit, or symbol. They are stored using the ASCII value of the symbol and typically occupy 1 byte of memory. Characters represent a single character, such as a letter, digit, or symbol. They are stored using the ASCII value of the symbol and typically occupy 1 byte of memory.
Example: Example:
@ -42,7 +42,7 @@ Example:
char letter = 'A'; char letter = 'A';
``` ```
### Boolean (bool) ## Boolean (bool)
Booleans represent logical values: `true` or `false`. They usually occupy 1 byte of memory. Booleans represent logical values: `true` or `false`. They usually occupy 1 byte of memory.
Example: Example:
@ -54,7 +54,7 @@ bool is_cpp_great = true;
Derived data types are types that are derived from fundamental data types. Some examples include: Derived data types are types that are derived from fundamental data types. Some examples include:
### Arrays ## Arrays
Arrays are used to store multiple values of the same data type in consecutive memory locations. Arrays are used to store multiple values of the same data type in consecutive memory locations.
Example: Example:
@ -62,7 +62,7 @@ Example:
int numbers[5] = {1, 2, 3, 4, 5}; int numbers[5] = {1, 2, 3, 4, 5};
``` ```
### Pointers ## Pointers
Pointers are used to store the memory address of a variable. Pointers are used to store the memory address of a variable.
Example: Example:
@ -71,7 +71,7 @@ int num = 42;
int* pNum = &num; int* pNum = &num;
``` ```
### References ## References
References are an alternative way to share memory locations between variables, allowing you to create an alias for another variable. References are an alternative way to share memory locations between variables, allowing you to create an alias for another variable.
Example: Example:
@ -84,7 +84,7 @@ int& numRef = num;
User-defined data types are types that are defined by the programmer, such as structures, classes, and unions. User-defined data types are types that are defined by the programmer, such as structures, classes, and unions.
### Structures (struct) ## Structures (struct)
Structures are used to group variables of different data types together under a single name. Structures are used to group variables of different data types together under a single name.
Example: Example:
@ -98,7 +98,7 @@ struct Person {
Person p1 = {"John Doe", 30, 5.9}; Person p1 = {"John Doe", 30, 5.9};
``` ```
### Classes (class) ## Classes (class)
Classes are similar to structures, but they can also have member functions and access specifiers. Classes are similar to structures, but they can also have member functions and access specifiers.
Example: Example:
@ -118,7 +118,7 @@ p1.name = "John Doe";
p1.age = 30; p1.age = 30;
``` ```
### Unions (union) ## Unions (union)
Unions are used to store different data types in the same memory location. Unions are used to store different data types in the same memory location.
Example: Example:

@ -1,7 +1,7 @@
# References # References
A reference can be considered as a constant pointer (not to be confused with a pointer to a constant value) which always points to (references) the same object. They are declared using the `&` (ampersand) symbol. A reference can be considered as a constant pointer (not to be confused with a pointer to a constant value) which always points to (references) the same object. They are declared using the `&` (ampersand) symbol.
### Declaration and Initialization ## Declaration and Initialization
To declare a reference, use the `&` symbol followed by the variable type and the reference's name. Note that you must initialize a reference when you declare it. To declare a reference, use the `&` symbol followed by the variable type and the reference's name. Note that you must initialize a reference when you declare it.
```cpp ```cpp
@ -9,7 +9,7 @@ int var = 10; // Declare an integer variable
int& ref = var; // Declare a reference that "points to" var int& ref = var; // Declare a reference that "points to" var
``` ```
### Usage ## Usage
You can use the reference just like you'd use the original variable. When you change the value of the reference, the value of the original variable also changes, because they both share the same memory location. You can use the reference just like you'd use the original variable. When you change the value of the reference, the value of the original variable also changes, because they both share the same memory location.
```cpp ```cpp
@ -20,7 +20,7 @@ ref = 30; // Sets the value of ref to 30
cout << var << endl; // Outputs 30 cout << var << endl; // Outputs 30
``` ```
### Function Parameters ## Function Parameters
You can use references as function parameters to create an alias for an argument. This is commonly done when you need to modify the original variable or when passing an object of considerable size to avoid the cost of copying. You can use references as function parameters to create an alias for an argument. This is commonly done when you need to modify the original variable or when passing an object of considerable size to avoid the cost of copying.
```cpp ```cpp
void swap(int& a, int& b) { void swap(int& a, int& b) {

@ -2,7 +2,7 @@
Object lifetime refers to the time during which an object exists, from the moment it is created until it is destroyed. In C++, an object's lifetime can be classified into four categories: Object lifetime refers to the time during which an object exists, from the moment it is created until it is destroyed. In C++, an object's lifetime can be classified into four categories:
1. **Static Storage Duration**: Objects with static storage duration exist for the entire run of the program. These objects are allocated at the beginning of the program's run and deallocated when the program terminates. Global variables, static data members, and static local variables fall into this category. - **Static Storage Duration**: Objects with static storage duration exist for the entire run of the program. These objects are allocated at the beginning of the program's run and deallocated when the program terminates. Global variables, static data members, and static local variables fall into this category.
```cpp ```cpp
int global_var; // Static storage duration int global_var; // Static storage duration
@ -14,13 +14,13 @@ Object lifetime refers to the time during which an object exists, from the momen
} }
``` ```
2. **Thread Storage Duration**: Objects with thread storage duration exist for the lifetime of the thread they belong to. They are created when a thread starts and destroyed when the thread exits. Thread storage duration can be specified using the `thread_local` keyword. - **Thread Storage Duration**: Objects with thread storage duration exist for the lifetime of the thread they belong to. They are created when a thread starts and destroyed when the thread exits. Thread storage duration can be specified using the `thread_local` keyword.
```cpp ```cpp
thread_local int my_var; // Thread storage duration thread_local int my_var; // Thread storage duration
``` ```
3. **Automatic Storage Duration**: Objects with automatic storage duration are created at the point of definition and destroyed when the scope in which they are declared is exited. These objects are also known as "local" or "stack" objects. Function parameters and local non-static variables fall into this category. - **Automatic Storage Duration**: Objects with automatic storage duration are created at the point of definition and destroyed when the scope in which they are declared is exited. These objects are also known as "local" or "stack" objects. Function parameters and local non-static variables fall into this category.
```cpp ```cpp
void myFunction() { void myFunction() {
@ -28,7 +28,7 @@ Object lifetime refers to the time during which an object exists, from the momen
} }
``` ```
4. **Dynamic Storage Duration**: Objects with dynamic storage duration are created at runtime, using memory allocation functions such as `new` or `malloc`. The lifetime of these objects must be managed manually, as they are not automatically deallocated when the scope is exited. Instead, it is the programmer's responsibility to destroy the objects using the `delete` or `free` functions when they are no longer needed, to avoid memory leaks. - **Dynamic Storage Duration**: Objects with dynamic storage duration are created at runtime, using memory allocation functions such as `new` or `malloc`. The lifetime of these objects must be managed manually, as they are not automatically deallocated when the scope is exited. Instead, it is the programmer's responsibility to destroy the objects using the `delete` or `free` functions when they are no longer needed, to avoid memory leaks.
```cpp ```cpp
int* ptr = new int; // Dynamic storage duration int* ptr = new int; // Dynamic storage duration

@ -2,7 +2,7 @@
Raw pointers in C++ are low-level constructs that directly hold a memory address. They can be used for manually allocating memory, creating dynamic arrays, and passing values efficiently, among other things. Raw pointers in C++ are low-level constructs that directly hold a memory address. They can be used for manually allocating memory, creating dynamic arrays, and passing values efficiently, among other things.
### `new` Operator ##`new` Operator
The `new` operator is used to allocate memory on the heap. The memory allocated using `new` remains available until you explicitly deallocate it using the corresponding `delete` operator. The `new` operator is used to allocate memory on the heap. The memory allocated using `new` remains available until you explicitly deallocate it using the corresponding `delete` operator.
@ -13,7 +13,7 @@ int* ptr = new int; // Dynamically allocates an int on the heap
*ptr = 42; // Assigns the value 42 to the allocated int *ptr = 42; // Assigns the value 42 to the allocated int
``` ```
### `delete` Operator ##`delete` Operator
The `delete` operator is used to deallocate memory that has been allocated using `new`. After memory is deallocated, it's available to be reallocated for other purposes. Failing to properly deallocate memory can lead to memory leaks. The `delete` operator is used to deallocate memory that has been allocated using `new`. After memory is deallocated, it's available to be reallocated for other purposes. Failing to properly deallocate memory can lead to memory leaks.
@ -26,7 +26,7 @@ int* ptr = new int; // Dynamically allocates an int on the heap
delete ptr; // Deallocates the memory assigned to ptr delete ptr; // Deallocates the memory assigned to ptr
``` ```
### `new[]` and `delete[]` Operators ##`new[]` and `delete[]` Operators
The `new[]` and `delete[]` operators are used for allocating and deallocating memory for an array of objects. The syntax for `new[]` and `delete[]` is very similar to that of `new` and `delete`. The `new[]` and `delete[]` operators are used for allocating and deallocating memory for an array of objects. The syntax for `new[]` and `delete[]` is very similar to that of `new` and `delete`.

@ -4,7 +4,7 @@ A `shared_ptr` is a type of smart pointer in C++ that allows multiple pointers t
When using a `shared_ptr`, the reference counter is automatically incremented every time a new pointer is created, and decremented when each pointer goes out of scope. Once the reference counter reaches zero, the system will clean up the memory. When using a `shared_ptr`, the reference counter is automatically incremented every time a new pointer is created, and decremented when each pointer goes out of scope. Once the reference counter reaches zero, the system will clean up the memory.
### Code Example ## Code Example
Here's an example of how to use `shared_ptr`: Here's an example of how to use `shared_ptr`:

@ -2,7 +2,7 @@
In C++, a namespace is a named scope or container that is used to organize and enclose a collection of code elements, such as variables, functions, classes, and other namespaces. They are mainly used to divide and manage the code base, giving developers control over name collisions and the specialization of code. In C++, a namespace is a named scope or container that is used to organize and enclose a collection of code elements, such as variables, functions, classes, and other namespaces. They are mainly used to divide and manage the code base, giving developers control over name collisions and the specialization of code.
### Syntax ## Syntax
Here's the syntax for declaring a namespace: Here's the syntax for declaring a namespace:
@ -12,11 +12,11 @@ namespace identifier {
} }
``` ```
### Using Namespaces ## Using Namespaces
To access elements within a namespace, you can use the scope resolution operator `::`. Here are some examples: To access elements within a namespace, you can use the scope resolution operator `::`. Here are some examples:
#### Declaring and accessing a namespace ### Declaring and accessing a namespace
```cpp ```cpp
#include <iostream> #include <iostream>
@ -34,7 +34,7 @@ int main() {
} }
``` ```
#### Nesting namespaces ### Nesting namespaces
Namespaces can be nested within other namespaces: Namespaces can be nested within other namespaces:
@ -57,11 +57,11 @@ int main() {
} }
``` ```
### `using` Keyword ##`using` Keyword
You can use the `using` keyword to import namespaced elements into the current scope. However, this might lead to name conflicts if multiple namespaces have elements with the same name. You can use the `using` keyword to import namespaced elements into the current scope. However, this might lead to name conflicts if multiple namespaces have elements with the same name.
#### Using a single element from a namespace ### Using a single element from a namespace
```cpp ```cpp
#include <iostream> #include <iostream>
@ -80,7 +80,7 @@ int main() {
} }
``` ```
#### Using the entire namespace ### Using the entire namespace
```cpp ```cpp
#include <iostream> #include <iostream>

@ -2,7 +2,7 @@
**Scope** refers to the visibility and accessibility of variables, functions, classes, and other identifiers in a C++ program. It determines the lifetime and extent of these identifiers. In C++, there are four types of scope: **Scope** refers to the visibility and accessibility of variables, functions, classes, and other identifiers in a C++ program. It determines the lifetime and extent of these identifiers. In C++, there are four types of scope:
1. **Global scope:** Identifiers declared outside any function or class have a global scope. They can be accessed from any part of the program (unless hidden by a local identifier with the same name). The lifetime of a global identifier is the entire duration of the program. - **Global scope:** Identifiers declared outside any function or class have a global scope. They can be accessed from any part of the program (unless hidden by a local identifier with the same name). The lifetime of a global identifier is the entire duration of the program.
```cpp ```cpp
#include <iostream> #include <iostream>
@ -14,7 +14,7 @@ int main() {
} }
``` ```
2. **Local scope:** Identifiers declared within a function or a block have a local scope. They can be accessed only within the function or the block they were declared in. Their lifetime is limited to the duration of the function/block execution. - **Local scope:** Identifiers declared within a function or a block have a local scope. They can be accessed only within the function or the block they were declared in. Their lifetime is limited to the duration of the function/block execution.
```cpp ```cpp
#include <iostream> #include <iostream>
@ -31,7 +31,7 @@ int main() {
} }
``` ```
3. **Namespace scope:** A namespace is a named scope that groups related identifiers together. Identifiers declared within a namespace have the namespace scope. They can be accessed using the namespace name and the scope resolution operator `::`. - **Namespace scope:** A namespace is a named scope that groups related identifiers together. Identifiers declared within a namespace have the namespace scope. They can be accessed using the namespace name and the scope resolution operator `::`.
```cpp ```cpp
#include <iostream> #include <iostream>
@ -45,7 +45,7 @@ int main() {
} }
``` ```
4. **Class scope:** Identifiers declared within a class have a class scope. They can be accessed using the class name and the scope resolution operator `::` or, for non-static members, an object of the class and the dot `.` or arrow `->` operator. - **Class scope:** Identifiers declared within a class have a class scope. They can be accessed using the class name and the scope resolution operator `::` or, for non-static members, an object of the class and the dot `.` or arrow `->` operator.
```cpp ```cpp
#include <iostream> #include <iostream>

@ -2,7 +2,7 @@
Forward declaration is a way of declaring a symbol (class, function, or variable) before defining it in the code. It helps the compiler understand the type, size, and existence of the symbol. This declaration is particularly useful when we have cyclic dependencies or to reduce compilation time by avoiding unnecessary header inclusions in the source file. Forward declaration is a way of declaring a symbol (class, function, or variable) before defining it in the code. It helps the compiler understand the type, size, and existence of the symbol. This declaration is particularly useful when we have cyclic dependencies or to reduce compilation time by avoiding unnecessary header inclusions in the source file.
### Class Forward Declaration ## Class Forward Declaration
To use a class type before it is defined, you can declare the class without defining its members, like this: To use a class type before it is defined, you can declare the class without defining its members, like this:
@ -23,7 +23,7 @@ public:
However, if you try to make an object of `ClassA` or call its member functions without defining the class, you will get a compilation error. However, if you try to make an object of `ClassA` or call its member functions without defining the class, you will get a compilation error.
### Function Forward Declaration ## Function Forward Declaration
Functions must be declared before using them, and a forward declaration can be used to declare a function without defining it: Functions must be declared before using them, and a forward declaration can be used to declare a function without defining it:
@ -40,7 +40,7 @@ int add(int a, int b) {
} }
``` ```
### Enum and Typedef Forward Declaration ## Enum and Typedef Forward Declaration
For `enum` and `typedef`, it is not possible to forward declare because they don't have separate declaration and definition stages. For `enum` and `typedef`, it is not possible to forward declare because they don't have separate declaration and definition stages.

@ -2,7 +2,7 @@
Code splitting refers to the process of breaking down a large code base into smaller, more manageable files or modules. This helps improve the organization, maintainability, and readability of the code. In C++, code splitting is generally achieved through the use of separate compilation, header files, and source files. Code splitting refers to the process of breaking down a large code base into smaller, more manageable files or modules. This helps improve the organization, maintainability, and readability of the code. In C++, code splitting is generally achieved through the use of separate compilation, header files, and source files.
#### Header Files (.h or .hpp) ### Header Files (.h or .hpp)
Header files, usually with the `.h` or `.hpp` extension, are responsible for declaring classes, functions, and variables that are needed by multiple source files. They act as an interface between different parts of the code, making it easier to manage dependencies and reduce the chances of duplicated code. Header files, usually with the `.h` or `.hpp` extension, are responsible for declaring classes, functions, and variables that are needed by multiple source files. They act as an interface between different parts of the code, making it easier to manage dependencies and reduce the chances of duplicated code.
@ -21,7 +21,7 @@ public:
#endif #endif
``` ```
#### Source Files (.cpp) ### Source Files (.cpp)
Source files, with the `.cpp` extension, are responsible for implementing the actual functionality defined in the corresponding header files. They include the header files as needed and provide the function and class method definitions. Source files, with the `.cpp` extension, are responsible for implementing the actual functionality defined in the corresponding header files. They include the header files as needed and provide the function and class method definitions.
@ -37,7 +37,7 @@ void Example::printMessage() {
} }
``` ```
#### Separate Compilation ### Separate Compilation
C++ allows for separate compilation, which means that each source file can be compiled independently into an object file. These object files can then be linked together to form the final executable. This provides faster build times when making changes to a single source file since only that file needs to be recompiled, and the other object files can be reused. C++ allows for separate compilation, which means that each source file can be compiled independently into an object file. These object files can then be linked together to form the final executable. This provides faster build times when making changes to a single source file since only that file needs to be recompiled, and the other object files can be reused.

@ -23,9 +23,9 @@ In this example, MyResource is a simple structure that does not manage any resou
The Rule of Three states that a class or structure that manages resources should define the following three special member functions: The Rule of Three states that a class or structure that manages resources should define the following three special member functions:
1. Destructor - Destructor
2. Copy constructor - Copy constructor
3. Copy assignment operator - Copy assignment operator
These functions are necessary for proper resource management, such as releasing memory or correctly handling deep copies. These functions are necessary for proper resource management, such as releasing memory or correctly handling deep copies.
@ -61,8 +61,8 @@ In this example, MyResource is a class that manages a resource (an array of inte
The Rule of Five extends the Rule of Three to include two additional special member functions: The Rule of Five extends the Rule of Three to include two additional special member functions:
1. Move constructor - Move constructor
2. Move assignment operator - Move assignment operator
Modern C++ introduces move semantics, which allows for more efficient handling of resources by transferring ownership without necessarily copying all the data. Modern C++ introduces move semantics, which allows for more efficient handling of resources by transferring ownership without necessarily copying all the data.

@ -2,7 +2,7 @@
Static polymorphism, also known as compile-time polymorphism, is a type of polymorphism that resolves the types and method calls at compile time rather than at runtime. This is commonly achieved through the use of function overloading and templates in C++. Static polymorphism, also known as compile-time polymorphism, is a type of polymorphism that resolves the types and method calls at compile time rather than at runtime. This is commonly achieved through the use of function overloading and templates in C++.
### Function Overloading ## Function Overloading
Function overloading is a way to create multiple functions with the same name but different parameter lists. The compiler determines the correct function to call based on the types and number of arguments used when the function is called. Function overloading is a way to create multiple functions with the same name but different parameter lists. The compiler determines the correct function to call based on the types and number of arguments used when the function is called.
@ -32,7 +32,7 @@ int main() {
} }
``` ```
### Templates ## Templates
Templates are a powerful feature in C++ that allows you to create generic functions or classes. The actual code for specific types is generated at compile time, which avoids the overhead of runtime polymorphism. The use of templates is the main technique to achieve static polymorphism in C++. Templates are a powerful feature in C++ that allows you to create generic functions or classes. The actual code for specific types is generated at compile time, which avoids the overhead of runtime polymorphism. The use of templates is the main technique to achieve static polymorphism in C++.

@ -4,7 +4,7 @@ Function overloading is a type of static polymorphism in C++ where multiple func
To overload a function, simply define another function with the same name but a different set of parameters. The compiler will automatically choose the correct function to call based on the provided arguments. To overload a function, simply define another function with the same name but a different set of parameters. The compiler will automatically choose the correct function to call based on the provided arguments.
### Examples ## Examples
Here's an example illustrating function overloading: Here's an example illustrating function overloading:

@ -4,7 +4,7 @@ Dynamic polymorphism is a programming concept in object-oriented languages like
Dynamic polymorphism is achieved through **virtual functions**, which are member functions of a base class marked with the `virtual` keyword. When you specify a virtual function in a base class, it can be overridden in any derived class to provide a different implementation. Dynamic polymorphism is achieved through **virtual functions**, which are member functions of a base class marked with the `virtual` keyword. When you specify a virtual function in a base class, it can be overridden in any derived class to provide a different implementation.
### Example ## Example
Here's an example in C++ demonstrating dynamic polymorphism. Here's an example in C++ demonstrating dynamic polymorphism.

@ -4,7 +4,7 @@ Virtual methods are a key aspect of dynamic polymorphism in C++. They allow subc
To declare a method as virtual, simply use the `virtual` keyword in the method's declaration in the base class. This tells the compiler that the method should be treated as a virtual method, allowing it to be overridden by derived classes. To declare a method as virtual, simply use the `virtual` keyword in the method's declaration in the base class. This tells the compiler that the method should be treated as a virtual method, allowing it to be overridden by derived classes.
### Code Example ## Code Example
Here's an example demonstrating virtual methods: Here's an example demonstrating virtual methods:

@ -4,7 +4,7 @@ Virtual Tables (or Vtable) are a mechanism used by C++ compilers to support dyna
When a class contains a virtual function, the compiler creates a virtual table for that class. This table contains function pointers to the virtual functions defined in the class. Each object of that class has a pointer to its virtual table (_vptr_, virtual pointer), which is automatically initialized by the compiler during object construction. When a class contains a virtual function, the compiler creates a virtual table for that class. This table contains function pointers to the virtual functions defined in the class. Each object of that class has a pointer to its virtual table (_vptr_, virtual pointer), which is automatically initialized by the compiler during object construction.
### Example ## Example
Let's consider the following example: Let's consider the following example:

@ -2,7 +2,7 @@
Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to perform operations and interact with each other. In C++, you can achieve OOP through the use of classes and objects. Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to perform operations and interact with each other. In C++, you can achieve OOP through the use of classes and objects.
### Classes ## Classes
A class is a blueprint for creating objects. It defines the structure (data members) and behavior (member functions) for a type of object. Here's an example of a simple class: A class is a blueprint for creating objects. It defines the structure (data members) and behavior (member functions) for a type of object. Here's an example of a simple class:
@ -27,7 +27,7 @@ myDog.age = 3;
myDog.bark(); // Output: Fido barks! myDog.bark(); // Output: Fido barks!
``` ```
### Encapsulation ## Encapsulation
Encapsulation is the concept of bundling data and functions that operate on that data within a single unit, such as a class. It helps to hide the internal implementation details of a class and expose only the necessary information and functionalities. In C++, you can use access specifiers like `public`, `private`, and `protected` to control the visibility and accessibility of class members. For example: Encapsulation is the concept of bundling data and functions that operate on that data within a single unit, such as a class. It helps to hide the internal implementation details of a class and expose only the necessary information and functionalities. In C++, you can use access specifiers like `public`, `private`, and `protected` to control the visibility and accessibility of class members. For example:
@ -54,7 +54,7 @@ public:
In this example, we've made the `name` and `age` data members `private` and added public member functions `setName` and `setAge` to modify them. This way, the internal data of the `Dog` class is protected and only accessible through the provided functions. In this example, we've made the `name` and `age` data members `private` and added public member functions `setName` and `setAge` to modify them. This way, the internal data of the `Dog` class is protected and only accessible through the provided functions.
### Inheritance ## Inheritance
Inheritance is the concept of deriving new classes from existing ones, which enables code reusability and organization. In C++, inheritance is achieved by using a colon `:` followed by the base class' access specifier and the base class name. For example: Inheritance is the concept of deriving new classes from existing ones, which enables code reusability and organization. In C++, inheritance is achieved by using a colon `:` followed by the base class' access specifier and the base class name. For example:
@ -82,7 +82,7 @@ myDog.breathe(); // Output: I can breathe
myDog.bark(); // Output: Dog barks! myDog.bark(); // Output: Dog barks!
``` ```
### Polymorphism ## Polymorphism
Polymorphism allows you to use a single interface to represent different types. In C++, it's mainly achieved using function overloading, virtual functions, and overriding. For example: Polymorphism allows you to use a single interface to represent different types. In C++, it's mainly achieved using function overloading, virtual functions, and overriding. For example:

@ -4,7 +4,7 @@ Multiple inheritance is a feature in C++ where a class can inherit characteristi
When a class inherits multiple base classes, it becomes a mixture of their properties and behaviors, and can override or extend them as needed. When a class inherits multiple base classes, it becomes a mixture of their properties and behaviors, and can override or extend them as needed.
### Syntax ## Syntax
Here is the syntax to declare a class with multiple inheritance: Here is the syntax to declare a class with multiple inheritance:
@ -17,7 +17,7 @@ class DerivedClass : access-specifier BaseClass1, access-specifier BaseClass2, .
The `DerivedClass` will inherit members from both `BaseClass1` and `BaseClass2`. The `access-specifier` (like `public`, `protected`, or `private`) determines the accessibility of the inherited members. The `DerivedClass` will inherit members from both `BaseClass1` and `BaseClass2`. The `access-specifier` (like `public`, `protected`, or `private`) determines the accessibility of the inherited members.
### Example ## Example
Here is an example of multiple inheritance in action: Here is an example of multiple inheritance in action:
@ -69,7 +69,7 @@ int main()
} }
``` ```
### Note ## Note
In some cases, multiple inheritance can lead to complications such as ambiguity and the "diamond problem". Ensure that you use multiple inheritance judiciously and maintain well-structured and modular classes to prevent issues. In some cases, multiple inheritance can lead to complications such as ambiguity and the "diamond problem". Ensure that you use multiple inheritance judiciously and maintain well-structured and modular classes to prevent issues.

@ -2,29 +2,29 @@
An access violation is a specific type of error that occurs when a program attempts to access an illegal memory location. In C++, access violations are most commonly caused by: An access violation is a specific type of error that occurs when a program attempts to access an illegal memory location. In C++, access violations are most commonly caused by:
1. **Dereferencing a null or invalid pointer.** - **Dereferencing a null or invalid pointer.**
2. **Accessing an array out of bounds.** - **Accessing an array out of bounds.**
3. **Reading or writing to memory freed by the user or the operating system.** - **Reading or writing to memory freed by the user or the operating system.**
It is crucial to identify access violations because they can lead to unpredictable behavior, application crashes, or corruption of data. It is crucial to identify access violations because they can lead to unpredictable behavior, application crashes, or corruption of data.
#### Examples Some examples of access violations are:
##### 1. Dereferencing null or invalid pointer ## Dereferencing null or invalid pointer
```cpp ```cpp
int *p = nullptr; int *p = nullptr;
int x = *p; // Access violation: trying to access null pointer's content int x = *p; // Access violation: trying to access null pointer's content
``` ```
##### 2. Accessing an array out of bounds ## Accessing an array out of bounds
```cpp ```cpp
int arr[5] = {1, 2, 3, 4, 5}; int arr[5] = {1, 2, 3, 4, 5};
int y = arr[5]; // Access violation: index out of bounds (valid indices are 0-4) int y = arr[5]; // Access violation: index out of bounds (valid indices are 0-4)
``` ```
##### 3. Reading or writing to freed memory ## Reading or writing to freed memory
```cpp ```cpp
int* p2 = new int[10]; int* p2 = new int[10];
@ -32,7 +32,7 @@ delete[] p2;
p2[3] = 42; // Access violation: writing to memory that has been freed p2[3] = 42; // Access violation: writing to memory that has been freed
``` ```
#### Debugging Access Violations ### Debugging Access Violations
Tools like _debuggers_, _static analyzers_, and _profilers_ can help identify access violations in your code. For example: Tools like _debuggers_, _static analyzers_, and _profilers_ can help identify access violations in your code. For example:

@ -6,7 +6,7 @@ Exit codes, also known as "return codes" or "status codes", are numeric values t
In C++, you can return an exit code from the `main` function by using the `return` statement, or you can use the `exit()` function, which is part of the C++ Standard Library. In C++, you can return an exit code from the `main` function by using the `return` statement, or you can use the `exit()` function, which is part of the C++ Standard Library.
### Example: Using return in `main` ## Example: Using return in `main`
```cpp ```cpp
#include <iostream> #include <iostream>
@ -30,7 +30,7 @@ int main() {
} }
``` ```
### Example: Using the `exit()` function ## Example: Using the `exit()` function
```cpp ```cpp
#include <iostream> #include <iostream>

@ -2,7 +2,7 @@
`static_cast` is one of the casting operators in C++ that allows you to convert between different data types, such as integer and float, or between pointer types. This type of cast performs a compile-time check and gives an error if there is no valid conversion possible between given types. `static_cast` is generally safer than C-style casts since it does not perform an unsafe reinterpretation of data and allows for better type checking. `static_cast` is one of the casting operators in C++ that allows you to convert between different data types, such as integer and float, or between pointer types. This type of cast performs a compile-time check and gives an error if there is no valid conversion possible between given types. `static_cast` is generally safer than C-style casts since it does not perform an unsafe reinterpretation of data and allows for better type checking.
### Syntax ## Syntax
The syntax for `static_cast` is as follows: The syntax for `static_cast` is as follows:
@ -10,16 +10,16 @@ The syntax for `static_cast` is as follows:
static_cast<new_type>(expression) static_cast<new_type>(expression)
``` ```
### Examples ## Examples
1. Converting between basic data types: - Converting between basic data types:
```cpp ```cpp
int i = 42; int i = 42;
float f = static_cast<float>(i); // Converts integer i to float f float f = static_cast<float>(i); // Converts integer i to float f
``` ```
2. Casting pointers of different object types in an inheritance hierarchy: - Casting pointers of different object types in an inheritance hierarchy:
```cpp ```cpp
class Base { /* ... */ }; class Base { /* ... */ };
@ -29,7 +29,7 @@ Base *bPtr = new Derived;
Derived *dPtr = static_cast<Derived *>(bPtr); // Converts Base pointer bPtr to Derived pointer dPtr Derived *dPtr = static_cast<Derived *>(bPtr); // Converts Base pointer bPtr to Derived pointer dPtr
``` ```
3. Converting an integer to an enumeration: - Converting an integer to an enumeration:
```cpp ```cpp
enum Color { RED, GREEN, BLUE }; enum Color { RED, GREEN, BLUE };

@ -4,7 +4,7 @@
Keep in mind that using `const_cast` to modify a truly `const` variable can lead to undefined behavior, so it is best to use this feature only when absolutely necessary. Keep in mind that using `const_cast` to modify a truly `const` variable can lead to undefined behavior, so it is best to use this feature only when absolutely necessary.
### Example ## Example
Here's a code example showing how to use `const_cast`: Here's a code example showing how to use `const_cast`:

@ -2,21 +2,21 @@
Type casting is the process of converting a value from one data type to another. In C++, there are four different methods of type casting: Type casting is the process of converting a value from one data type to another. In C++, there are four different methods of type casting:
1. **C-style casting**: It is the syntax inherited from C, and it is done by simply putting the target data type in parentheses before the value to cast. - **C-style casting**: It is the syntax inherited from C, and it is done by simply putting the target data type in parentheses before the value to cast.
Example: Example:
```cpp ```cpp
int a = 10; int a = 10;
float b = (float)a; // C-style cast from int to float float b = (float)a; // C-style cast from int to float
``` ```
2. **`static_cast`**: This is the most commonly used method for type casting in C++. It is performed at compile time, and you should use it when you have an explicit conversion between data types. - **`static_cast`**: This is the most commonly used method for type casting in C++. It is performed at compile time, and you should use it when you have an explicit conversion between data types.
Example: Example:
```cpp ```cpp
int a = 10; int a = 10;
float b = static_cast<float>(a); // static_cast from int to float float b = static_cast<float>(a); // static_cast from int to float
``` ```
3. **`dynamic_cast`**: This method is specifically used for safely converting pointers and references between base and derived classes in a class hierarchy. - **`dynamic_cast`**: This method is specifically used for safely converting pointers and references between base and derived classes in a class hierarchy.
Example: Example:
```cpp ```cpp
class Base {}; class Base {};
@ -26,14 +26,14 @@ Type casting is the process of converting a value from one data type to another.
Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); // dynamic_cast from Base* to Derived* Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); // dynamic_cast from Base* to Derived*
``` ```
4. **`reinterpret_cast`**: This cast changes the type of a pointer, reference, or an integer value. It is also called a bitwise cast because it changes how the compiler interprets the underlying bits. Use `reinterpret_cast` only when you have a deep understanding of what you're doing, as it does not guarantee that the resulting value will be meaningful. - **`reinterpret_cast`**: This cast changes the type of a pointer, reference, or an integer value. It is also called a bitwise cast because it changes how the compiler interprets the underlying bits. Use `reinterpret_cast` only when you have a deep understanding of what you're doing, as it does not guarantee that the resulting value will be meaningful.
Example: Example:
```cpp ```cpp
int* a = new int(42); int* a = new int(42);
long b = reinterpret_cast<long>(a); // reinterpret_cast from int* to long long b = reinterpret_cast<long>(a); // reinterpret_cast from int* to long
``` ```
5. **`const_cast`**: This casting method is used to remove the `const` qualifier from a variable. It is generally not recommended, but can be useful in certain situations where you have no control over the constness of a variable. - **`const_cast`**: This casting method is used to remove the `const` qualifier from a variable. It is generally not recommended, but can be useful in certain situations where you have no control over the constness of a variable.
Example: Example:
```cpp ```cpp
const int a = 10; const int a = 10;

@ -7,28 +7,28 @@ Undefined behavior in C++ refers to a situation where a program's behavior canno
Some common examples of Undefined Behavior are: Some common examples of Undefined Behavior are:
1. **Uninitialized Variables**: Accessing the value of an uninitialized variable can lead to undefined behavior. The value of an uninitialized variable is arbitrary and depends on what was in the memory location before the variable was declared. - **Uninitialized Variables**: Accessing the value of an uninitialized variable can lead to undefined behavior. The value of an uninitialized variable is arbitrary and depends on what was in the memory location before the variable was declared.
```cpp ```cpp
int x; int x;
int y = x + 5; // Undefined behavior since x is uninitialized int y = x + 5; // Undefined behavior since x is uninitialized
``` ```
2. **Out-of-bounds Memory Access**: Accessing memory outside the boundaries of an array or buffer may result in undefined behavior. - **Out-of-bounds Memory Access**: Accessing memory outside the boundaries of an array or buffer may result in undefined behavior.
```cpp ```cpp
int arr[5]; int arr[5];
int val = arr[5]; // Undefined behavior since the valid indices are 0 to 4 int val = arr[5]; // Undefined behavior since the valid indices are 0 to 4
``` ```
3. **Null Pointer Dereference**: Dereferencing a null pointer may lead to undefined behavior. - **Null Pointer Dereference**: Dereferencing a null pointer may lead to undefined behavior.
```cpp ```cpp
int *ptr = nullptr; int *ptr = nullptr;
int val = *ptr; // Undefined behavior since ptr is a null pointer int val = *ptr; // Undefined behavior since ptr is a null pointer
``` ```
4. **Division by Zero**: Performing a division operation by zero is undefined behavior in C++. - **Division by Zero**: Performing a division operation by zero is undefined behavior in C++.
```cpp ```cpp
int x = 5; int x = 5;

@ -4,7 +4,7 @@ Argument Dependent Lookup (ADL) or Koenig Lookup is a mechanism in C++ that allo
ADL allows the compiler to find functions in the same namespace as the arguments, even if the function is not declared at the point of use or within the namespace provided. This is especially useful when working with templates or generic programming. ADL allows the compiler to find functions in the same namespace as the arguments, even if the function is not declared at the point of use or within the namespace provided. This is especially useful when working with templates or generic programming.
### Example ## Example
Consider the following example using a namespace and overloaded `operator<<()`: Consider the following example using a namespace and overloaded `operator<<()`:

@ -4,7 +4,7 @@ Macros are preprocessing directives in C++ used by the preprocessor to perform t
Macros can be used to define constants, create function-like macros, or perform conditional compilation. Macros can be used to define constants, create function-like macros, or perform conditional compilation.
### Constant Macros ## Constant Macros
Constant macros are used to define symbolic constants for use in code. They do not use any memory and are replaced by the preprocessor before the compilation process. Constant macros are used to define symbolic constants for use in code. They do not use any memory and are replaced by the preprocessor before the compilation process.
@ -20,7 +20,7 @@ This macro defines a symbolic constant `PI`. You can use it in your code as if i
double circumference = 2 * PI * radius; double circumference = 2 * PI * radius;
``` ```
### Function-like Macros ## Function-like Macros
Function-like macros are similar to regular functions. They take a list of arguments and perform text substitution. Function-like macros are similar to regular functions. They take a list of arguments and perform text substitution.
@ -36,7 +36,7 @@ This macro defines a function-like macro `SQUARE` that calculates the square of
int square_of_five = SQUARE(5); // expands to ((5) * (5)) int square_of_five = SQUARE(5); // expands to ((5) * (5))
``` ```
### Conditional Compilation ## Conditional Compilation
Macros can be used for conditional compilation using the `#ifdef`, `#ifndef`, `#if`, `#else`, `#elif`, and `#endif` directives. Macros can be used for conditional compilation using the `#ifdef`, `#ifndef`, `#if`, `#else`, `#elif`, and `#endif` directives.

@ -2,7 +2,7 @@
C++ is a powerful, high-level, object-oriented programming language that offers several key language concepts. These concepts provide the foundation upon which you can build efficient, reliable, and maintainable programs. Here's a brief summary of some important language concepts in C++. C++ is a powerful, high-level, object-oriented programming language that offers several key language concepts. These concepts provide the foundation upon which you can build efficient, reliable, and maintainable programs. Here's a brief summary of some important language concepts in C++.
### 1. Variables and Data Types ## Variables and Data Types
C++ provides various fundamental data types such as `int`, `float`, `double`, `char`, and `bool` to declare and manipulate variables in a program. C++ provides various fundamental data types such as `int`, `float`, `double`, `char`, and `bool` to declare and manipulate variables in a program.
Example: Example:
@ -14,7 +14,7 @@ char grade = 'A';
bool isEmployed = true; bool isEmployed = true;
``` ```
### 2. Control Structures ## Control Structures
Control structures enable you to control the flow of execution of a program. Key control structures in C++ include: Control structures enable you to control the flow of execution of a program. Key control structures in C++ include:
- Conditional statement: `if`, `else`, and `else if` - Conditional statement: `if`, `else`, and `else if`
@ -36,7 +36,7 @@ for (int i = 0; i < 5; i++) {
} }
``` ```
### 3. Functions ## Functions
Functions in C++ allow you to break down a large program into small, manageable, and reusable pieces of code. Functions in C++ allow you to break down a large program into small, manageable, and reusable pieces of code.
Example: Example:
@ -52,7 +52,7 @@ int main() {
} }
``` ```
### 4. Arrays and Vectors ## Arrays and Vectors
Arrays and Vectors are commonly used data structures to store and manipulate a collection of elements of the same datatype. Arrays and Vectors are commonly used data structures to store and manipulate a collection of elements of the same datatype.
Example: Example:
@ -64,7 +64,7 @@ int marks[] = {90, 80, 95, 85};
vector<int> scores = {10, 20, 30, 40}; vector<int> scores = {10, 20, 30, 40};
``` ```
### 5. Pointers ## Pointers
Pointers are variables that store memory addresses of other variables. They enable more efficient handling of memory, and are useful for working with dynamic data structures. Pointers are variables that store memory addresses of other variables. They enable more efficient handling of memory, and are useful for working with dynamic data structures.
Example: Example:
@ -73,7 +73,7 @@ int num = 10;
int* p = &num; // p stores the address of num int* p = &num; // p stores the address of num
``` ```
### 6. Structures and Classes ## Structures and Classes
Structures and Classes are user-defined data types that allow grouping of variables and functions under a single name. Structures and Classes are user-defined data types that allow grouping of variables and functions under a single name.
Example: Example:
@ -95,7 +95,7 @@ public:
}; };
``` ```
### 7. Inheritance and Polymorphism ## Inheritance and Polymorphism
Inheritance is a mechanism that allows a class to inherit properties and methods from a base class. Polymorphism enables you to use a base class type to represent derived class objects. Inheritance is a mechanism that allows a class to inherit properties and methods from a base class. Polymorphism enables you to use a base class type to represent derived class objects.
Example: Example:
@ -115,7 +115,7 @@ public:
}; };
``` ```
### 8. Exception Handling ## Exception Handling
C++ provides a mechanism to handle exceptions(runtime errors) gracefully using `try`, `catch`, and `throw` constructs. C++ provides a mechanism to handle exceptions(runtime errors) gracefully using `try`, `catch`, and `throw` constructs.
Example: Example:

@ -4,7 +4,7 @@ Iterators are objects in the C++ Standard Library (`STL`) that help us traverse
There are different types of iterators which you would encounter depending on their use cases: There are different types of iterators which you would encounter depending on their use cases:
1. **Input Iterator**: Used to read elements in a container only once, in a forward direction. They cannot modify elements. - **Input Iterator**: Used to read elements in a container only once, in a forward direction. They cannot modify elements.
Example: Example:
@ -14,7 +14,7 @@ std::istream_iterator<int> input(std::cin);
std::copy(input, std::istream_iterator<int>(), std::back_inserter(nums)); std::copy(input, std::istream_iterator<int>(), std::back_inserter(nums));
``` ```
2. **Output Iterator**: Used to write elements in a container only once, in a forward direction. They cannot re-write elements. - **Output Iterator**: Used to write elements in a container only once, in a forward direction. They cannot re-write elements.
Example: Example:
@ -24,7 +24,7 @@ std::ostream_iterator<int> output(std::cout, ", ");
std::copy(nums.begin(), nums.end(), output); std::copy(nums.begin(), nums.end(), output);
``` ```
3. **Forward Iterator**: Similar to input iterators but can be used for multiple passes over the elements in a container. They cannot move backward. - **Forward Iterator**: Similar to input iterators but can be used for multiple passes over the elements in a container. They cannot move backward.
Example: Example:
@ -37,7 +37,7 @@ while (itr != nums.end()) {
} }
``` ```
4. **Bidirectional Iterator**: These iterators offer the ability to move both forward and backward in a container. List and set containers have bi-directional iterators. - **Bidirectional Iterator**: These iterators offer the ability to move both forward and backward in a container. List and set containers have bi-directional iterators.
Example: Example:
@ -52,7 +52,7 @@ for (--itr; itr != nums.begin(); --itr) {
} }
``` ```
5. **Random Access Iterator**: These iterators provide the most flexible ways to access elements in a container. They can move forwards, backwards, jump directly to other elements, and access elements at a given index. - **Random Access Iterator**: These iterators provide the most flexible ways to access elements in a container. They can move forwards, backwards, jump directly to other elements, and access elements at a given index.
Example: Example:

@ -4,11 +4,11 @@ The Standard Template Library (STL) in C++ provides a collection of generic algo
## Key Concepts ## Key Concepts
### Sorting ## Sorting
Sorting refers to arranging a sequence of elements in a specific order. The STL provides several sorting algorithms, such as `std::sort`, `std::stable_sort`, and `std::partial_sort`. Sorting refers to arranging a sequence of elements in a specific order. The STL provides several sorting algorithms, such as `std::sort`, `std::stable_sort`, and `std::partial_sort`.
#### std::sort ### std::sort
`std::sort` is used to sort a range of elements [first, last) in non-descending order (by default). You can also use custom comparison functions or lambda expressions to change the sorting order. `std::sort` is used to sort a range of elements [first, last) in non-descending order (by default). You can also use custom comparison functions or lambda expressions to change the sorting order.
@ -30,11 +30,11 @@ int main() {
} }
``` ```
### Searching ## Searching
Searching refers to finding if a particular element is present within a given range of elements. STL provides various searching algorithms, such as `std::find`, `std::binary_search`, and `std::find_if`. Searching refers to finding if a particular element is present within a given range of elements. STL provides various searching algorithms, such as `std::find`, `std::binary_search`, and `std::find_if`.
#### std::find ### std::find
`std::find` is used to find the iterator of the first occurrence of a given value within the range [first, last). `std::find` is used to find the iterator of the first occurrence of a given value within the range [first, last).
@ -58,11 +58,11 @@ int main() {
} }
``` ```
### Modifying Sequences ## Modifying Sequences
The STL also provides algorithms for modifying sequences, such as `std::remove`, `std::replace`, and `std::unique`. The STL also provides algorithms for modifying sequences, such as `std::remove`, `std::replace`, and `std::unique`.
#### std::remove ### std::remove
`std::remove` is used to remove all instances of a value from a container within the given range [first, last). Note that the function does not resize the container after removing elements. `std::remove` is used to remove all instances of a value from a container within the given range [first, last). Note that the function does not resize the container after removing elements.

@ -2,7 +2,7 @@
In C++, you can work with dates and times using the `chrono` library, which is part of the Standard Library (STL). The `chrono` library provides various data types and functions to represent and manipulate time durations, time points, and clocks. In C++, you can work with dates and times using the `chrono` library, which is part of the Standard Library (STL). The `chrono` library provides various data types and functions to represent and manipulate time durations, time points, and clocks.
### Duration ## Duration
A `duration` represents a span of time, which can be expressed in various units such as seconds, minutes, hours, etc. To create a duration, use the `std::chrono::duration` template class. Common predefined duration types are: A `duration` represents a span of time, which can be expressed in various units such as seconds, minutes, hours, etc. To create a duration, use the `std::chrono::duration` template class. Common predefined duration types are:
@ -24,7 +24,7 @@ int main() {
} }
``` ```
### Time Point ## Time Point
A `time_point` represents a specific point in time. It is usually created using a combination of duration and a clock. In C++, there are three clock types provided by the `chrono` library: A `time_point` represents a specific point in time. It is usually created using a combination of duration and a clock. In C++, there are three clock types provided by the `chrono` library:
@ -44,7 +44,7 @@ int main() {
} }
``` ```
### Clock ## Clock
A clock provides access to the current time. It consists of the following elements: A clock provides access to the current time. It consists of the following elements:
@ -68,7 +68,7 @@ int main() {
} }
``` ```
### Converting Time Points to Calendar Time ## Converting Time Points to Calendar Time
To convert a time point to calendar representation, you can use the `std::chrono::system_clock::to_time_t` function. To convert a time point to calendar representation, you can use the `std::chrono::system_clock::to_time_t` function.

@ -4,7 +4,7 @@ Multithreading is the concurrent execution of multiple threads within a single p
In C++, multithreading support is available through the `thread` library introduced in the C++11 standard. In C++, multithreading support is available through the `thread` library introduced in the C++11 standard.
### Basic Thread Creation ## Basic Thread Creation
To create a new thread, include the `<thread>` header file and create an instance of `std::thread` that takes a function as an argument. The function will be executed in a new thread. To create a new thread, include the `<thread>` header file and create an instance of `std::thread` that takes a function as an argument. The function will be executed in a new thread.
@ -23,7 +23,7 @@ int main() {
} }
``` ```
### Thread with Arguments ## Thread with Arguments
You can pass arguments to the thread function by providing them as additional arguments to the `std::thread` constructor. You can pass arguments to the thread function by providing them as additional arguments to the `std::thread` constructor.
@ -42,7 +42,7 @@ int main() {
} }
``` ```
### Mutex and Locks ## Mutex and Locks
When multiple threads access shared resources, there is a possibility of a data race. To avoid this, use mutex and locks to synchronize shared resource access. When multiple threads access shared resources, there is a possibility of a data race. To avoid this, use mutex and locks to synchronize shared resource access.

@ -6,7 +6,7 @@ C++ Containers are a part of the Standard Template Library (STL) that provide da
Vectors are dynamic arrays that can resize themselves as needed. They store elements in a contiguous memory location, allowing fast random access using indices. Vectors are dynamic arrays that can resize themselves as needed. They store elements in a contiguous memory location, allowing fast random access using indices.
### Example ## Example
```cpp ```cpp
#include <iostream> #include <iostream>
@ -29,7 +29,7 @@ int main() {
A list is a doubly-linked list that allows elements to be inserted or removed from any position in constant time. It does not support random access. Lists are better than vectors for scenarios where you need to insert or remove elements in the middle frequently. A list is a doubly-linked list that allows elements to be inserted or removed from any position in constant time. It does not support random access. Lists are better than vectors for scenarios where you need to insert or remove elements in the middle frequently.
### Example ## Example
```cpp ```cpp
#include <iostream> #include <iostream>
@ -52,7 +52,7 @@ int main() {
A map is an associative container that stores key-value pairs. It supports the retrieval of values based on their keys. The keys are sorted in ascending order by default. A map is an associative container that stores key-value pairs. It supports the retrieval of values based on their keys. The keys are sorted in ascending order by default.
### Example ## Example
```cpp ```cpp
#include <iostream> #include <iostream>
@ -75,7 +75,7 @@ int main() {
Similar to a map, an unordered map stores key-value pairs, but it is implemented using a hash table. This means unordered_map has faster average-case performance compared to map, since it does not maintain sorted order. However, worst-case performance can be worse than map. Similar to a map, an unordered map stores key-value pairs, but it is implemented using a hash table. This means unordered_map has faster average-case performance compared to map, since it does not maintain sorted order. However, worst-case performance can be worse than map.
### Example ## Example
```cpp ```cpp
#include <iostream> #include <iostream>

@ -6,7 +6,7 @@ The C++ Standard Template Library (STL) is a collection of header files that pro
Containers are the data structures used for data storage and manipulation in C++. They are classified into four types: sequence containers, associative containers, unordered associative containers, and container adaptors. Containers are the data structures used for data storage and manipulation in C++. They are classified into four types: sequence containers, associative containers, unordered associative containers, and container adaptors.
1. **Sequence Containers**: These are linear data structures that store elements in a sequential manner. Examples include: - **Sequence Containers**: These are linear data structures that store elements in a sequential manner. Examples include:
- `std::vector`: A dynamic array that grows and shrinks at runtime. - `std::vector`: A dynamic array that grows and shrinks at runtime.
```cpp ```cpp
std::vector<int> my_vector; std::vector<int> my_vector;
@ -20,7 +20,7 @@ Containers are the data structures used for data storage and manipulation in C++
std::deque<int> my_deque; std::deque<int> my_deque;
``` ```
2. **Associative Containers**: These containers store data in a sorted manner with unique keys. Examples include: - **Associative Containers**: These containers store data in a sorted manner with unique keys. Examples include:
- `std::set`: A collection of unique elements sorted by keys. - `std::set`: A collection of unique elements sorted by keys.
```cpp ```cpp
std::set<int> my_set; std::set<int> my_set;
@ -30,7 +30,7 @@ Containers are the data structures used for data storage and manipulation in C++
std::map<std::string, int> my_map; std::map<std::string, int> my_map;
``` ```
3. **Unordered Associative Containers**: These containers store data in an unordered manner using hash tables. Examples include: - **Unordered Associative Containers**: These containers store data in an unordered manner using hash tables. Examples include:
- `std::unordered_set`: A collection of unique elements in no specific order. - `std::unordered_set`: A collection of unique elements in no specific order.
```cpp ```cpp
std::unordered_set<int> my_unordered_set; std::unordered_set<int> my_unordered_set;
@ -40,7 +40,7 @@ Containers are the data structures used for data storage and manipulation in C++
std::unordered_map<std::string, int> my_unordered_map; std::unordered_map<std::string, int> my_unordered_map;
``` ```
4. **Container Adaptors**: These are containers based on other existing containers. Examples include: - **Container Adaptors**: These are containers based on other existing containers. Examples include:
- `std::stack`: A LIFO data structure based on deque or list. - `std::stack`: A LIFO data structure based on deque or list.
```cpp ```cpp
std::stack<int> my_stack; std::stack<int> my_stack;

@ -2,7 +2,7 @@
Variadic templates are a feature in C++11 that allows you to define a template with a variable number of arguments. This is especially useful when you need to write a function or class that can accept different numbers and types of arguments. Variadic templates are a feature in C++11 that allows you to define a template with a variable number of arguments. This is especially useful when you need to write a function or class that can accept different numbers and types of arguments.
### Syntax ## Syntax
The syntax for variadic templates is very simple. To define a variadic template, use the `...` (ellipsis) notation: The syntax for variadic templates is very simple. To define a variadic template, use the `...` (ellipsis) notation:
@ -12,9 +12,9 @@ template <typename... Args>
This notation represents a parameter pack, which can contain zero or more arguments. You can use this parameter pack as a variable list of template parameters in your template definition. This notation represents a parameter pack, which can contain zero or more arguments. You can use this parameter pack as a variable list of template parameters in your template definition.
### Examples ## Examples
#### Summing Multiple Arguments Using Variadic Templates ### Summing Multiple Arguments Using Variadic Templates
```cpp ```cpp
#include <iostream> #include <iostream>
@ -39,7 +39,7 @@ int main() {
} }
``` ```
#### Tuple Class Using Variadic Templates ### Tuple Class Using Variadic Templates
```cpp ```cpp
template <typename... Types> template <typename... Types>

@ -2,7 +2,7 @@
Full template specialization allows you to provide a specific implementation, or behavior, for a template when used with a certain set of type parameters. It is useful when you want to handle special cases or optimize your code for specific types. Full template specialization allows you to provide a specific implementation, or behavior, for a template when used with a certain set of type parameters. It is useful when you want to handle special cases or optimize your code for specific types.
### Syntax ## Syntax
To create a full specialization of a template, you need to define the specific type for which the specialization should happen. The syntax looks as follows: To create a full specialization of a template, you need to define the specific type for which the specialization should happen. The syntax looks as follows:
```cpp ```cpp
@ -10,7 +10,7 @@ template <> //Indicates that this is a specialization
className<specificType> //The specialized class for the specific type className<specificType> //The specialized class for the specific type
``` ```
### Example ## Example
Consider the following example to demonstrate full template specialization: Consider the following example to demonstrate full template specialization:
```cpp ```cpp

@ -4,11 +4,11 @@ Template specialization is a way to customize or modify the behavior of a templa
There are two main ways you can specialize a template: There are two main ways you can specialize a template:
1. **Full specialization:** This occurs when you provide a specific implementation for a specific type or set of types. - **Full specialization:** This occurs when you provide a specific implementation for a specific type or set of types.
2. **Partial specialization:** This occurs when you provide a more general implementation for a subset of types that match a certain pattern or condition. - **Partial specialization:** This occurs when you provide a more general implementation for a subset of types that match a certain pattern or condition.
### Full Template Specialization ## Full Template Specialization
Full specialization is used when you want to create a separate implementation of a template for a specific type. To do this, you need to use keyword `template<>` followed by the function template with the desired specialized type. Full specialization is used when you want to create a separate implementation of a template for a specific type. To do this, you need to use keyword `template<>` followed by the function template with the desired specialized type.
@ -35,7 +35,7 @@ int main() {
} }
``` ```
### Partial Template Specialization ## Partial Template Specialization
Partial specialization is used when you want to create a separate implementation of a template for a subset of types that match a certain pattern or condition. Partial specialization is used when you want to create a separate implementation of a template for a subset of types that match a certain pattern or condition.

@ -9,7 +9,7 @@ Some common type traits are:
- `std::is_function`: Checks if the given type is a function type. - `std::is_function`: Checks if the given type is a function type.
- `std::decay`: Applies decltype rules to the input type ( strips references, cv-qualifiers, etc. ). - `std::decay`: Applies decltype rules to the input type ( strips references, cv-qualifiers, etc. ).
### Usage ## Usage
You can use type traits like this: You can use type traits like this:
@ -28,7 +28,7 @@ int main() {
} }
``` ```
### Composing Type Traits ## Composing Type Traits
Some type traits help you compose other traits or modify them, such as: Some type traits help you compose other traits or modify them, such as:

@ -4,7 +4,7 @@ SFINAE is a principle in C++ template metaprogramming that allows the compiler t
The key idea behind SFINAE is that if a substitution error occurs, it is silently ignored, and the compiler continues to explore other template specializations or overloads. This allows you to write more flexible and generic code, as it enables you to have multiple specializations for different scenarios. The key idea behind SFINAE is that if a substitution error occurs, it is silently ignored, and the compiler continues to explore other template specializations or overloads. This allows you to write more flexible and generic code, as it enables you to have multiple specializations for different scenarios.
### Code Example ## Code Example
Here's an example that demonstrates SFINAE in action: Here's an example that demonstrates SFINAE in action:

@ -2,7 +2,7 @@
Templates in C++ are a powerful feature that allows you to write generic code, meaning that you can write a single function or class that can work with different data types. This means you do not need to write separate functions or classes for each data type you want to work with. Templates in C++ are a powerful feature that allows you to write generic code, meaning that you can write a single function or class that can work with different data types. This means you do not need to write separate functions or classes for each data type you want to work with.
### Template Functions ## Template Functions
To create a template function, you use the `template` keyword followed by the type parameters or placeholders enclosed in angle brackets (`< >`). Then, you define your function as you normally would, using the type parameters to specify the generic types. To create a template function, you use the `template` keyword followed by the type parameters or placeholders enclosed in angle brackets (`< >`). Then, you define your function as you normally would, using the type parameters to specify the generic types.
@ -27,7 +27,7 @@ Or, you can let the compiler deduce the type for you:
int result = max(10, 20); int result = max(10, 20);
``` ```
### Template Classes ## Template Classes
Similarly, you can create template classes using the `template` keyword. Here's an example of a simple template class that represents a pair of values: Similarly, you can create template classes using the `template` keyword. Here's an example of a simple template class that represents a pair of values:
@ -48,7 +48,7 @@ To use this class, you need to specify the type parameters when creating an obje
Pair<int, std::string> pair(1, "Hello"); Pair<int, std::string> pair(1, "Hello");
``` ```
### Template Specialization ## Template Specialization
Sometimes, you may need special behavior for a specific data type. In this case, you can use template specialization. For example, you can specialize the `Pair` class for a specific type, like `char`: Sometimes, you may need special behavior for a specific data type. In this case, you can use template specialization. For example, you can specialize the `Pair` class for a specific type, like `char`:

@ -2,7 +2,7 @@
RAII is a popular idiom in C++ that focuses on using the object's life cycle to manage resources. It encourages binding the resource lifetime to the scope of a corresponding object so that it's automatically acquired when an object is created and released when the object is destroyed. This helps in simplifying the code, avoiding leaks and managing resources efficiently. RAII is a popular idiom in C++ that focuses on using the object's life cycle to manage resources. It encourages binding the resource lifetime to the scope of a corresponding object so that it's automatically acquired when an object is created and released when the object is destroyed. This helps in simplifying the code, avoiding leaks and managing resources efficiently.
### Code Examples ## Code Examples
Here's an example of using RAII to manage resources, specifically a dynamically allocated array: Here's an example of using RAII to manage resources, specifically a dynamically allocated array:

@ -2,7 +2,7 @@
Pimpl (Pointer-to-Implementation) idiom, also known as a private class data, compiler firewall, or handle classes, is a technique used in C++ to hide the implementation details of a class by using a forward declaration to a private structure or class, keeping the public interface of the class clean, and reducing compile-time dependencies. Pimpl (Pointer-to-Implementation) idiom, also known as a private class data, compiler firewall, or handle classes, is a technique used in C++ to hide the implementation details of a class by using a forward declaration to a private structure or class, keeping the public interface of the class clean, and reducing compile-time dependencies.
### Implementation ## Implementation
Here is a simple example illustrating the Pimpl idiom: Here is a simple example illustrating the Pimpl idiom:

@ -3,8 +3,8 @@
The erase-remove idiom is a common C++ technique to efficiently remove elements from a container, particularly from standard sequence containers like `std::vector`, `std::list`, and `std::deque`. It leverages the standard library algorithms `std::remove` (or `std::remove_if`) and the member function `erase()`. The erase-remove idiom is a common C++ technique to efficiently remove elements from a container, particularly from standard sequence containers like `std::vector`, `std::list`, and `std::deque`. It leverages the standard library algorithms `std::remove` (or `std::remove_if`) and the member function `erase()`.
The idiom consists of two steps: The idiom consists of two steps:
1. `std::remove` (or `std::remove_if`) moves the elements to be removed towards the end of the container and returns an iterator pointing to the first element to remove. - `std::remove` (or `std::remove_if`) moves the elements to be removed towards the end of the container and returns an iterator pointing to the first element to remove.
2. `container.erase()` removes the elements from the container using the iterator obtained in the previous step. - `container.erase()` removes the elements from the container using the iterator obtained in the previous step.
Here's an example: Here's an example:

@ -4,9 +4,9 @@ Copy-swap is a C++ idiom that leverages the copy constructor and swap function t
Here's a brief summary: Here's a brief summary:
1. **Copy**: Create a local copy of the right-hand side object. This step leverages the copy constructor, providing exception safety and code reuse. - **Copy**: Create a local copy of the right-hand side object. This step leverages the copy constructor, providing exception safety and code reuse.
2. **Swap**: Swap the contents of the left-hand side object with the temporary copy. This step typically involves swapping internal pointers or resources, without needing to copy the full contents again. - **Swap**: Swap the contents of the left-hand side object with the temporary copy. This step typically involves swapping internal pointers or resources, without needing to copy the full contents again.
3. **Destruction**: Destroy the temporary copy. This happens upon the exit of the assignment operator. - **Destruction**: Destroy the temporary copy. This happens upon the exit of the assignment operator.
Here's a code example for a simple `String` class: Here's a code example for a simple `String` class:
@ -30,8 +30,8 @@ class String {
``` ```
Using the copy-swap idiom: Using the copy-swap idiom:
1. The right-hand side object is copied when passed by value to the assignment operator. - The right-hand side object is copied when passed by value to the assignment operator.
2. The left-hand side object's contents are swapped with the temporary copy. - The left-hand side object's contents are swapped with the temporary copy.
3. The temporary copy is destroyed, releasing any resources that were previously held by the left-hand side object. - The temporary copy is destroyed, releasing any resources that were previously held by the left-hand side object.
This approach simplifies the implementation and provides strong exception safety, while reusing the copy constructor and destructor code. This approach simplifies the implementation and provides strong exception safety, while reusing the copy constructor and destructor code.

@ -2,7 +2,7 @@
C++17, also known as C++1z, is the version of the C++ programming language published in December 2017. It builds upon the previous standard, C++14, and adds various new features and enhancements to improve the language's expressiveness, performance, and usability. C++17, also known as C++1z, is the version of the C++ programming language published in December 2017. It builds upon the previous standard, C++14, and adds various new features and enhancements to improve the language's expressiveness, performance, and usability.
### Key Features: ## Key Features:
- If-init-statement: Introduces a new syntax for writing conditions with scope inside if and switch statements. - If-init-statement: Introduces a new syntax for writing conditions with scope inside if and switch statements.
```cpp ```cpp
if(auto it = map.find(key); it != map.end()) if(auto it = map.find(key); it != map.end())

@ -4,7 +4,7 @@ C++20 is the latest standard of the C++ programming language, which brings signi
Here are some of the key features introduced in C++20: Here are some of the key features introduced in C++20:
### Concepts ## Concepts
Concepts are a way to enforce specific requirements on template parameters, allowing you to write more expressive and understandable code. They improve the error messages when using templates and ensure that the template parameters fulfill specific criteria. Concepts are a way to enforce specific requirements on template parameters, allowing you to write more expressive and understandable code. They improve the error messages when using templates and ensure that the template parameters fulfill specific criteria.
@ -20,7 +20,7 @@ T add(T a, T b) {
} }
``` ```
### Ranges ## Ranges
Ranges provide a new way to work with sequences of values, enhancing the power and expressiveness of the Standard Library algorithms. The range-based algorithms make it easier and more convenient to work with sequences. Ranges provide a new way to work with sequences of values, enhancing the power and expressiveness of the Standard Library algorithms. The range-based algorithms make it easier and more convenient to work with sequences.
@ -41,7 +41,7 @@ int main() {
} }
``` ```
### Coroutines ## Coroutines
Coroutines are a new way to write asynchronous and concurrent code with improved readability. They allow functions to be suspended and resumed, enabling you to write more efficient, non-blocking code. Coroutines are a new way to write asynchronous and concurrent code with improved readability. They allow functions to be suspended and resumed, enabling you to write more efficient, non-blocking code.
@ -61,7 +61,7 @@ int main() {
} }
``` ```
### The `constexpr` and `consteval` Keywords ## The `constexpr` and `consteval` Keywords
Both `constexpr` and `consteval` are related to compile-time evaluation. Functions marked with `constexpr` can be executed at compile-time or runtime, while functions marked with `consteval` can only be executed at compile-time. Both `constexpr` and `consteval` are related to compile-time evaluation. Functions marked with `constexpr` can be executed at compile-time or runtime, while functions marked with `consteval` can only be executed at compile-time.

@ -2,7 +2,7 @@
C++20 is the newest standard of the C++ programming language, which was officially published in December 2020. It introduces many new features, enhancements, and improvements over the previous standards. Here is a brief summary of some key features in C++20. C++20 is the newest standard of the C++ programming language, which was officially published in December 2020. It introduces many new features, enhancements, and improvements over the previous standards. Here is a brief summary of some key features in C++20.
1. **Concepts**: Concepts provide a way to specify constraints on template parameters, ensuring that they meet a specific set of requirements. This allows for better compile-time error messages and code readability. - **Concepts**: Concepts provide a way to specify constraints on template parameters, ensuring that they meet a specific set of requirements. This allows for better compile-time error messages and code readability.
Example: Example:
``` ```
@ -17,7 +17,7 @@ C++20 is the newest standard of the C++ programming language, which was official
} }
``` ```
2. **Ranges**: Ranges build on the iterator concept and provide a more usable and composable framework for dealing with sequences of values. They simplify the way algorithms can be applied to collections of data. - **Ranges**: Ranges build on the iterator concept and provide a more usable and composable framework for dealing with sequences of values. They simplify the way algorithms can be applied to collections of data.
Example: Example:
``` ```
@ -35,7 +35,7 @@ C++20 is the newest standard of the C++ programming language, which was official
} }
``` ```
3. **Coroutines**: Coroutines offer a way to split complex, long-running functions into smaller, more manageable chunks, allowing them to be suspended and resumed at specific points. - **Coroutines**: Coroutines offer a way to split complex, long-running functions into smaller, more manageable chunks, allowing them to be suspended and resumed at specific points.
Example: Example:
``` ```
@ -53,7 +53,7 @@ C++20 is the newest standard of the C++ programming language, which was official
} }
``` ```
4. **Lambdas with template parameters**: C++20 enables using `auto` as a lambda parameter, allowing for generic lambdas with templated parameters. - **Lambdas with template parameters**: C++20 enables using `auto` as a lambda parameter, allowing for generic lambdas with templated parameters.
Example: Example:
``` ```
@ -65,7 +65,7 @@ C++20 is the newest standard of the C++ programming language, which was official
double res2 = sum(1.0, 2.0); // double double res2 = sum(1.0, 2.0); // double
``` ```
5. **Constexpr enhancements**: `constexpr` support is extended with additional features, such as `constexpr` dynamic allocations, `constexpr` try-catch blocks, and `constexpr` lambdas. - **Constexpr enhancements**: `constexpr` support is extended with additional features, such as `constexpr` dynamic allocations, `constexpr` try-catch blocks, and `constexpr` lambdas.
Example: Example:
``` ```

@ -4,9 +4,9 @@ C++ standards are a set of rules and guidelines that define the language's featu
Here's a brief summary of the different C++ standards released to date: Here's a brief summary of the different C++ standards released to date:
1. **C++98/C++03**: The first standardized version of C++, which introduced many features like templates, exceptions, and the Standard Template Library (STL). C++03 is a minor update to C++98 with some bug fixes and performance improvements. - **C++98/C++03**: The first standardized version of C++, which introduced many features like templates, exceptions, and the Standard Template Library (STL). C++03 is a minor update to C++98 with some bug fixes and performance improvements.
2. **C++11**: A major upgrade to the language, which introduced features such as: - **C++11**: A major upgrade to the language, which introduced features such as:
- Lambda expressions: - Lambda expressions:
```cpp ```cpp
auto sum = [](int a, int b) -> int { return a + b; }; auto sum = [](int a, int b) -> int { return a + b; };
@ -20,7 +20,7 @@ Here's a brief summary of the different C++ standards released to date:
``` ```
- Smart pointers like `std::shared_ptr` and `std::unique_ptr`. - Smart pointers like `std::shared_ptr` and `std::unique_ptr`.
3. **C++14**: A minor update to C++11, which added features such as: - **C++14**: A minor update to C++11, which added features such as:
- Generic lambda expressions: - Generic lambda expressions:
```cpp ```cpp
auto generic_sum = [](auto a, auto b) { return a + b; }; auto generic_sum = [](auto a, auto b) { return a + b; };
@ -30,7 +30,7 @@ Here's a brief summary of the different C++ standards released to date:
int binary_number = 0b1010; int binary_number = 0b1010;
``` ```
4. **C++17**: Another major update that introduced features such as: - **C++17**: Another major update that introduced features such as:
- `if` and `switch` with initializers: - `if` and `switch` with initializers:
```cpp ```cpp
if (auto it = my_map.find(key); it != my_map.end()) { if (auto it = my_map.find(key); it != my_map.end()) {
@ -45,7 +45,7 @@ Here's a brief summary of the different C++ standards released to date:
} }
``` ```
5. **C++20**: The latest major update to the language, with features such as: - **C++20**: The latest major update to the language, with features such as:
- Concepts: - Concepts:
```cpp ```cpp
template<typename T> template<typename T>

@ -2,9 +2,9 @@
Debugger messages are notifications or alerts provided by a debugger to help you identify problems or errors in your C++ code. These messages can be warnings or error messages and can provide helpful information about the state of your program and specific issues encountered during the debugging process. Debugger messages are notifications or alerts provided by a debugger to help you identify problems or errors in your C++ code. These messages can be warnings or error messages and can provide helpful information about the state of your program and specific issues encountered during the debugging process.
### Types of Debugger Messages ## Types of Debugger Messages
1. **Error Messages:** Notify you about issues in the code that prevent the program from running or compiling correctly. These messages typically include information about the file and the line number where the error is detected, followed by a description of the issue. - **Error Messages:** Notify you about issues in the code that prevent the program from running or compiling correctly. These messages typically include information about the file and the line number where the error is detected, followed by a description of the issue.
Example: Example:
``` ```
@ -14,7 +14,7 @@ Debugger messages are notifications or alerts provided by a debugger to help you
^~~~ ^~~~
``` ```
2. **Warning Messages:** Inform you about potential issues or risky programming practices that may not necessarily cause errors but could lead to problems later on. Like error messages, warning messages usually include information about the file and line number where the issue is found, along with a description of the problem. - **Warning Messages:** Inform you about potential issues or risky programming practices that may not necessarily cause errors but could lead to problems later on. Like error messages, warning messages usually include information about the file and line number where the issue is found, along with a description of the problem.
Example: Example:
``` ```
@ -24,7 +24,7 @@ Debugger messages are notifications or alerts provided by a debugger to help you
^ ^
``` ```
3. **Informational Messages:** Provide general information about the execution of the program, such as breakpoints, watchpoints, and variable values. These messages can also reveal the current state of the program, including the call stack and the list of active threads. - **Informational Messages:** Provide general information about the execution of the program, such as breakpoints, watchpoints, and variable values. These messages can also reveal the current state of the program, including the call stack and the list of active threads.
Example (*assuming you are using GDB as debugger*): Example (*assuming you are using GDB as debugger*):
``` ```
@ -35,7 +35,7 @@ Debugger messages are notifications or alerts provided by a debugger to help you
Breakpoint 1, main () at test.cpp:5 Breakpoint 1, main () at test.cpp:5
5 int a = 5; 5 int a = 5;
``` ```
### Code Examples ## Code Examples
To make use of debugger messages, you need to employ a debugger, such as GDB or Visual Studio Debugger, and include specific flags during the compilation process. To make use of debugger messages, you need to employ a debugger, such as GDB or Visual Studio Debugger, and include specific flags during the compilation process.

@ -4,11 +4,11 @@ Debugger symbols are additional information embedded within the compiled program
There are generally two types of debugging symbols: There are generally two types of debugging symbols:
1. **Internal Debugging Symbols**: These symbols reside within the compiled binary code itself. When using internal debugging symbols, it is essential to note that the size of the binary increases, which may not be desirable for production environments. - **Internal Debugging Symbols**: These symbols reside within the compiled binary code itself. When using internal debugging symbols, it is essential to note that the size of the binary increases, which may not be desirable for production environments.
2. **External Debugging Symbols**: The debugging symbols are kept in separate files apart from the binary code, usually with file extensions such as `.pdb` (Program Database) in Windows or `.dSYM` (DWARF Symbol Information) in macOS. - **External Debugging Symbols**: The debugging symbols are kept in separate files apart from the binary code, usually with file extensions such as `.pdb` (Program Database) in Windows or `.dSYM` (DWARF Symbol Information) in macOS.
### Generating Debugger Symbols ## Generating Debugger Symbols
To generate debugger symbols in C++, you need to specify specific options during the compilation process. We will use `g++` compiler as an example. To generate debugger symbols in C++, you need to specify specific options during the compilation process. We will use `g++` compiler as an example.

@ -2,11 +2,11 @@
WinDbg is a powerful debugger for Windows applications, which is included in the Microsoft Windows SDK. It provides an extensive set of features to help you analyze and debug complex programs, kernel mode, and user-mode code. With a user-friendly graphical interface, WinDbg can help in analyzing crash dumps, setting breakpoints, and stepping through code execution. WinDbg is a powerful debugger for Windows applications, which is included in the Microsoft Windows SDK. It provides an extensive set of features to help you analyze and debug complex programs, kernel mode, and user-mode code. With a user-friendly graphical interface, WinDbg can help in analyzing crash dumps, setting breakpoints, and stepping through code execution.
### Getting Started ## Getting Started
To begin using WinDbg, you first need to install it. You can download the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/) and install it to get the WinDbg. To begin using WinDbg, you first need to install it. You can download the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/) and install it to get the WinDbg.
### Loading Symbols ## Loading Symbols
WinDbg relies on symbol files (*.pdb) to provide more useful information about a program's internal structures, functions, and variables. To load symbols properly, you may need to configure the symbol path: WinDbg relies on symbol files (*.pdb) to provide more useful information about a program's internal structures, functions, and variables. To load symbols properly, you may need to configure the symbol path:
@ -16,11 +16,11 @@ WinDbg relies on symbol files (*.pdb) to provide more useful information about a
.reload /f .reload /f
``` ```
### Opening Executables and Crash Dumps ## Opening Executables and Crash Dumps
To debug an executable using WinDbg, go to `File > Open Executable...`, then locate and open the target program. To analyze a crash dump, use `File > Open Crash Dump...` instead. To debug an executable using WinDbg, go to `File > Open Executable...`, then locate and open the target program. To analyze a crash dump, use `File > Open Crash Dump...` instead.
### Basic Commands ## Basic Commands
Some common commands you might use in WinDbg: Some common commands you might use in WinDbg:
@ -37,15 +37,15 @@ Some common commands you might use in WinDbg:
- `da`: Display memory contents as ASCII strings - `da`: Display memory contents as ASCII strings
- `!analyze -v`: Analyze the program state and provide detailed information - `!analyze -v`: Analyze the program state and provide detailed information
### Example Usage ## Example Usage
Debugging a simple program: Debugging a simple program:
1. Open the executable in WinDbg - Open the executable in WinDbg
2. Set a breakpoint using `bp <address>` - Set a breakpoint using `bp <address>`
3. Run the program using `g` - Run the program using `g`
4. Once the breakpoint is hit, use `t` or `p` to step through the code - Once the breakpoint is hit, use `t` or `p` to step through the code
5. Try `k` to view the call stack, or `dd`, `da` to inspect memory - Try `k` to view the call stack, or `dd`, `da` to inspect memory
6. Remove the breakpoint and continue debugging with other commands as needed - Remove the breakpoint and continue debugging with other commands as needed
Remember that WinDbg has a wealth of commands and functionality, so it's essential to get comfortable with the [documentation](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools) and explore the wealth of available resources specific to your debugging tasks. Remember that WinDbg has a wealth of commands and functionality, so it's essential to get comfortable with the [documentation](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools) and explore the wealth of available resources specific to your debugging tasks.

@ -2,7 +2,7 @@
GDB, or the GNU Project Debugger, is a powerful command-line debugger used primarily for C, C++, and other languages. It can help you find runtime errors, examine the program's execution state, and manipulate the flow to detect and fix bugs easily. GDB, or the GNU Project Debugger, is a powerful command-line debugger used primarily for C, C++, and other languages. It can help you find runtime errors, examine the program's execution state, and manipulate the flow to detect and fix bugs easily.
### Getting started with GDB ## Getting started with GDB
To start using GDB, you first need to compile your code with the `-g` flag, which includes debugging information in the executable: To start using GDB, you first need to compile your code with the `-g` flag, which includes debugging information in the executable:
@ -16,7 +16,7 @@ Now, you can load your compiled program into GDB:
gdb myfile gdb myfile
``` ```
### Basic GDB Commands ## Basic GDB Commands
Here are some common GDB commands you'll find useful when debugging: Here are some common GDB commands you'll find useful when debugging:
@ -30,7 +30,7 @@ Here are some common GDB commands you'll find useful when debugging:
- `frame [frame-number]`: Switch to a different stack frame. - `frame [frame-number]`: Switch to a different stack frame.
- `quit`: Exit GDB. - `quit`: Exit GDB.
### Example Usage ## Example Usage
Suppose you have a simple `cpp` file called `example.cpp`: Suppose you have a simple `cpp` file called `example.cpp`:

@ -2,11 +2,11 @@
Debuggers are essential tools for any C++ programmer, as they help in detecting, diagnosing, and fixing bugs in the code. They serve as an invaluable resource in identifying and understanding potential errors in the program. Debuggers are essential tools for any C++ programmer, as they help in detecting, diagnosing, and fixing bugs in the code. They serve as an invaluable resource in identifying and understanding potential errors in the program.
### Types of Debuggers ## Types of Debuggers
There are several debuggers available for use with C++: There are several debuggers available for use with C++:
1. **GDB (GNU Debugger):** This is the most widely used C++ debugger in the Linux environment. It can debug many languages, including C and C++. - **GDB (GNU Debugger):** This is the most widely used C++ debugger in the Linux environment. It can debug many languages, including C and C++.
Example usage: Example usage:
``` ```
@ -17,7 +17,7 @@ There are several debuggers available for use with C++:
next # step to the next line next # step to the next line
``` ```
2. **LLDB:** This is the debugger developed by LLVM. It supports multiple languages and is popular among macOS and iOS developers. - **LLDB:** This is the debugger developed by LLVM. It supports multiple languages and is popular among macOS and iOS developers.
Example usage: Example usage:
``` ```
@ -28,15 +28,15 @@ There are several debuggers available for use with C++:
next # step to the next line next # step to the next line
``` ```
3. **Microsoft Visual Studio Debugger:** This debugger is built into Visual Studio and is typically used in a graphical interface on Windows systems. - **Microsoft Visual Studio Debugger:** This debugger is built into Visual Studio and is typically used in a graphical interface on Windows systems.
Example usage: Example usage:
``` ```
Open your Visual Studio project and go to Debug > Start Debugging. Then use the step over (F10), step into (F11), or continue (F5) commands to navigate through the code. Open your Visual Studio project and go to Debug > Start Debugging. Then use the step over (F10), step into (F11), or continue (F5) commands to navigate through the code.
``` ```
4. **Intel Debugger (IDB):** This debugger is part of Intel's parallel development suite and is popular for high-performance applications. - **Intel Debugger (IDB):** This debugger is part of Intel's parallel development suite and is popular for high-performance applications.
5. **TotalView Debugger:** Developed by Rogue Wave Software, TotalView Debugger is a commercial debugger designed for parallel, high-performance, and enterprise applications. - **TotalView Debugger:** Developed by Rogue Wave Software, TotalView Debugger is a commercial debugger designed for parallel, high-performance, and enterprise applications.
Each debugger has its advantages and unique features, so it's essential to choose the one that best suits your needs and works well with your development environment. Each debugger has its advantages and unique features, so it's essential to choose the one that best suits your needs and works well with your development environment.

@ -2,7 +2,7 @@
The process of compilation in C++ can be divided into four primary stages: Preprocessing, Compilation, Assembly, and Linking. Each stage performs a specific task, ultimately converting the source code into an executable program. The process of compilation in C++ can be divided into four primary stages: Preprocessing, Compilation, Assembly, and Linking. Each stage performs a specific task, ultimately converting the source code into an executable program.
### 1. Preprocessing ## Preprocessing
The first stage is the preprocessing of the source code. Preprocessors modify the source code before the actual compilation process. They handle directives that start with a `#` (hash) symbol, like `#include`, `#define`, and `#if`. In this stage, included header files are expanded, macros are replaced, and conditional compilation statements are processed. The first stage is the preprocessing of the source code. Preprocessors modify the source code before the actual compilation process. They handle directives that start with a `#` (hash) symbol, like `#include`, `#define`, and `#if`. In this stage, included header files are expanded, macros are replaced, and conditional compilation statements are processed.
@ -18,7 +18,7 @@ int main() {
} }
``` ```
### 2. Compilation ## Compilation
The second stage is the actual compilation of the preprocessed source code. The compiler translates the modified source code into an intermediate representation, usually specific to the target processor architecture. This step also involves performing syntax checking, semantic analysis, and producing error messages for any issues encountered in the source code. The second stage is the actual compilation of the preprocessed source code. The compiler translates the modified source code into an intermediate representation, usually specific to the target processor architecture. This step also involves performing syntax checking, semantic analysis, and producing error messages for any issues encountered in the source code.
@ -33,7 +33,7 @@ int main() {
} }
``` ```
### 3. Assembly ## Assembly
The third stage is converting the compiler's intermediate representation into assembly language. This stage generates assembly code using mnemonics and syntax that is specific to the target processor architecture. Assemblers then convert this assembly code into object code (machine code). The third stage is converting the compiler's intermediate representation into assembly language. This stage generates assembly code using mnemonics and syntax that is specific to the target processor architecture. Assemblers then convert this assembly code into object code (machine code).
@ -45,7 +45,7 @@ The third stage is converting the compiler's intermediate representation into as
add eax, ebx add eax, ebx
``` ```
### 4. Linking ## Linking
The final stage is the linking of the object code with the necessary libraries and other object files. In this stage, the linker merges multiple object files and libraries, resolves external references from other modules or libraries, allocates memory addresses for functions and variables, and generates an executable file that can be run on the target platform. The final stage is the linking of the object code with the necessary libraries and other object files. In this stage, the linker merges multiple object files and libraries, resolves external references from other modules or libraries, allocates memory addresses for functions and variables, and generates an executable file that can be run on the target platform.

@ -1,86 +1,16 @@
# Features of C++ Compilers # Features of C++ Compilers
C++ compilers are responsible for transforming your human-readable C++ source code into machine-readable object code that can be executed by a computer. In this summary, we'll discuss different features of C++ compilers and, when applicable, provide code examples to illustrate them. Different C++ compilers have different features. Some of the most common features of C++ compilers are:
1. **Standards compliance**: C++ compilers adhere to standard specifications set forth by ISO/IEC, ensuring that your code remains consistent across different platforms and operating systems. The most recent C++ standard is C++20. - **Optimization:** Compilers can optimize the code to improve the performance of the program. For example, they can remove redundant code, inline functions, and perform loop unrolling.
- **Debugging:** Compilers can generate debugging information that can be used to debug the program.
- **Warnings:** Compilers can generate warnings for suspicious code that may cause errors.
Example: Some of the most popular C++ compilers are:
```cpp
// C++20 feature: concepts
template<typename T>
concept bool EqualityComparable = requires(T a, T b) {
{ a == b } -> bool;
{ a != b } -> bool;
};
```
2. **Cross-compilation**: C++ compilers allow you to create executable files for various target platforms, even if your development environment is different. - **GNU Compiler Collection (GCC):** GCC is a free and open-source compiler that supports many programming languages, including C++.
- **Clang:** Clang is a C++ compiler that is part of the LLVM project. It is designed to be compatible with GCC.
- **Microsoft Visual C++:** Microsoft Visual C++ is a C++ compiler that is part of the Microsoft Visual Studio IDE.
- **Intel C++ Compiler:** Intel C++ Compiler is a C++ compiler that is part of the Intel Parallel Studio XE suite.
3. **Optimization**: C++ compilers can perform various optimization techniques to improve the performance or reduce the size of your compiled executable. You should go through the documentation of your compiler to learn more about its features.
Example:
```cpp
// Compiler will likely optimize this loop
int sum = 0;
for (int i = 0; i < 10; ++i)
sum += i;
```
4. **Header files and libraries**: C++ compilers include standard libraries and support inclusion of custom header files or third-party libraries, which provide additional utilities and functions.
Example:
```cpp
#include <iostream> // Standard header for input/output operations
#include "custom_header.h" // Custom header
```
5. **Diagnostics**: C++ compilers produce diagnostic messages about errors or warnings in your source code to help you identify and fix issues.
Example:
```cpp
int main() {
// Compiler will produce a diagnostic message
// about the missing semicolon
int a = 5
int b = 10;
return 0;
}
```
6. **Debug and release configurations**: C++ compilers allow you to configure build settings for either debug or release mode, which helps you identify and fix bugs during development, or optimize your code for performance in the final version.
7. **Templates**: C++ compilers support a robust template system that allows you to write generic code which works with different data types, without function or class duplication.
Example:
```cpp
template<typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int result_int = add(1, 2);
double result_double = add(1.0, 2.0);
return 0;
}
```
8. **Language features**: C++ compilers support various language features, such as namespaces, classes, inheritance, polymorphism, exceptions, and more, making it possible to write clean, maintainable, and well-structured code.
Example:
```cpp
// C++ class and inheritance example
class Animal {
public:
virtual void talk() const = 0;
};
class Dog : public Animal {
public:
void talk() const override {
std::cout << "Woof!" << std::endl;
}
};
```
These are some of the key features you'll find in C++ compilers, which are essential for developing high-quality C++ applications efficiently.

@ -2,19 +2,19 @@
A compiler is a computer program that translates source code written in one programming language into a different language, usually machine code or assembly code, that can be executed directly by a computer's processor. In the context of C++, compilers take your written C++ source code and convert it into an executable program. A compiler is a computer program that translates source code written in one programming language into a different language, usually machine code or assembly code, that can be executed directly by a computer's processor. In the context of C++, compilers take your written C++ source code and convert it into an executable program.
### Popular C++ Compilers ## Popular C++ Compilers
There are several popular C++ compilers available, here's a short list of some common ones: There are several popular C++ compilers available, here's a short list of some common ones:
1. **GNU Compiler Collection (GCC)**: Developed by the GNU Project, GCC is an open-source compiler that supports multiple programming languages, including C++. - **GNU Compiler Collection (GCC)**: Developed by the GNU Project, GCC is an open-source compiler that supports multiple programming languages, including C++.
2. **Clang**: As part of the LLVM project, Clang is another open-source compiler that supports C++ and is known for its fast compilation times and extensive diagnostics. - **Clang**: As part of the LLVM project, Clang is another open-source compiler that supports C++ and is known for its fast compilation times and extensive diagnostics.
3. **Microsoft Visual C++ (MSVC)**: MSVC is a commercial compiler provided by Microsoft as part of Visual Studio, and it's widely used on Windows platforms. - **Microsoft Visual C++ (MSVC)**: MSVC is a commercial compiler provided by Microsoft as part of Visual Studio, and it's widely used on Windows platforms.
4. **Intel C++ Compiler (ICC)**: ICC is a commercial compiler provided by Intel and is known for its ability to optimize code for the latest Intel processors. - **Intel C++ Compiler (ICC)**: ICC is a commercial compiler provided by Intel and is known for its ability to optimize code for the latest Intel processors.
### Example of a Simple C++ Compilation ## Example of a Simple C++ Compilation
Let's say you have a simple C++ program saved in a file called `hello.cpp`: Let's say you have a simple C++ program saved in a file called `hello.cpp`:
@ -35,6 +35,6 @@ g++ hello.cpp -o hello
This will generate an executable file called `hello` (or `hello.exe` on Windows) which you can run to see the output "Hello, World!". This will generate an executable file called `hello` (or `hello.exe` on Windows) which you can run to see the output "Hello, World!".
### Note ## Note
When learning about compilers, it's essential to know that they work closely with the linker and the standard library. The linker takes care of combining compiled object files and libraries into a single executable, while the standard library provides implementations for common functionalities used in your code. When learning about compilers, it's essential to know that they work closely with the linker and the standard library. The linker takes care of combining compiled object files and libraries into a single executable, while the standard library provides implementations for common functionalities used in your code.

@ -2,7 +2,7 @@
CMake is a powerful cross-platform build system that generates build files, Makefiles, or workspaces for various platforms and compilers. Unlike the others build systems, CMake does not actually build the project, it only generates the files needed by build tools. CMake is widely used, particularly in C++ projects, for its ease of use and flexibility. CMake is a powerful cross-platform build system that generates build files, Makefiles, or workspaces for various platforms and compilers. Unlike the others build systems, CMake does not actually build the project, it only generates the files needed by build tools. CMake is widely used, particularly in C++ projects, for its ease of use and flexibility.
### CMakeLists.txt ## CMakeLists.txt
CMake uses a file called `CMakeLists.txt` to define settings, source files, libraries, and other configurations. A typical `CMakeLists.txt` for a simple project would look like: CMake uses a file called `CMakeLists.txt` to define settings, source files, libraries, and other configurations. A typical `CMakeLists.txt` for a simple project would look like:
@ -25,18 +25,18 @@ set_target_properties(${PROJECT_NAME} PROPERTIES
) )
``` ```
### Building with CMake ## Building with CMake
Here is an example of a simple build process using CMake: Here is an example of a simple build process using CMake:
1. Create a new directory for the build. - Create a new directory for the build.
```sh ```sh
mkdir build mkdir build
cd build cd build
``` ```
2. Generate build files using CMake. - Generate build files using CMake.
```sh ```sh
cmake .. cmake ..
@ -44,7 +44,7 @@ cmake ..
In this example, `..` indicates the parent directory where `CMakeLists.txt` is located. The build files will be generated in the `build` directory. In this example, `..` indicates the parent directory where `CMakeLists.txt` is located. The build files will be generated in the `build` directory.
3. Build the project using the generated build files. - Build the project using the generated build files.
```sh ```sh
make make

@ -4,15 +4,15 @@ A Makefile is a configuration file used by the `make` utility to automate the pr
Makefiles help developers save time, reduce errors, and ensure consistency in the build process. They achieve this by specifying the dependencies between different source files, and providing commands that generate output files (such as object files and executables) from input files (such as source code and headers). Makefiles help developers save time, reduce errors, and ensure consistency in the build process. They achieve this by specifying the dependencies between different source files, and providing commands that generate output files (such as object files and executables) from input files (such as source code and headers).
### Structure of a Makefile ## Structure of a Makefile
A typical Makefile has the following structure: A typical Makefile has the following structure:
1. **Variables**: Define variables to store commonly used values, such as compiler flags, directories, or target names. - **Variables**: Define variables to store commonly used values, such as compiler flags, directories, or target names.
2. **Rules**: Define how to generate output files from input files using a set of commands. Each rule has a *target*, a set of *prerequisites*, and a *recipe*. - **Rules**: Define how to generate output files from input files using a set of commands. Each rule has a *target*, a set of *prerequisites*, and a *recipe*.
3. **Phony targets**: Targets that do not represent actual files in the project but serve as a way to group related rules and invoke them using a single command. - **Phony targets**: Targets that do not represent actual files in the project but serve as a way to group related rules and invoke them using a single command.
### Example ## Example
Consider a basic C++ project with the following directory structure: Consider a basic C++ project with the following directory structure:
@ -50,6 +50,6 @@ clean:
With this Makefile, you can simply run `make` in the terminal to build the project, and `make clean` to remove the output files. The Makefile specifies the dependencies between the source code, object files, and the final executable, as well as the commands to compile and link them. With this Makefile, you can simply run `make` in the terminal to build the project, and `make clean` to remove the output files. The Makefile specifies the dependencies between the source code, object files, and the final executable, as well as the commands to compile and link them.
### Summary ## Summary
Makefiles provide a powerful way to automate building C++ projects using the `make` utility. They describe the dependencies and commands required to generate output files from source code, saving time and ensuring consistency in the build process. Makefiles provide a powerful way to automate building C++ projects using the `make` utility. They describe the dependencies and commands required to generate output files from source code, saving time and ensuring consistency in the build process.

@ -2,7 +2,7 @@
A build system is a collection of tools and utilities that automate the process of compiling, linking, and executing source code files in a project. The primary goal of build systems is to manage the complexity of the compilation process and produce a build (executable or binary files) in the end. In C++ (cpp), some common build systems are: A build system is a collection of tools and utilities that automate the process of compiling, linking, and executing source code files in a project. The primary goal of build systems is to manage the complexity of the compilation process and produce a build (executable or binary files) in the end. In C++ (cpp), some common build systems are:
1. **GNU Make**: It is a popular build system that uses `Makefile` to define the build process. It checks the dependencies and timestamps of source files to determine which files need to be compiled and linked. - **GNU Make**: It is a popular build system that uses `Makefile` to define the build process. It checks the dependencies and timestamps of source files to determine which files need to be compiled and linked.
Code example: Code example:
@ -21,7 +21,7 @@ A build system is a collection of tools and utilities that automate the process
rm $(TARGET) rm $(TARGET)
``` ```
2. **CMake**: It is a cross-platform build system that focuses on defining project dependencies and managing build environments. CMake generates build files (like Makefiles) for different platforms and allows developers to write source code once and then compile it for different target platforms. - **CMake**: It is a cross-platform build system that focuses on defining project dependencies and managing build environments. CMake generates build files (like Makefiles) for different platforms and allows developers to write source code once and then compile it for different target platforms.
Code example: Code example:
@ -34,7 +34,7 @@ A build system is a collection of tools and utilities that automate the process
add_executable(HelloWorld main.cpp) add_executable(HelloWorld main.cpp)
``` ```
3. **Autotools**: Also known as GNU Build System, consists of the GNU Autoconf, Automake, and Libtool tools that enable developers to create portable software across different Unix-based systems. For a C++ project, you will need to create `configure.ac`, `Makefile.am` files with specific rules, and then run the following commands in the terminal to build the project: - **Autotools**: Also known as GNU Build System, consists of the GNU Autoconf, Automake, and Libtool tools that enable developers to create portable software across different Unix-based systems. For a C++ project, you will need to create `configure.ac`, `Makefile.am` files with specific rules, and then run the following commands in the terminal to build the project:
``` ```
autoreconf --install autoreconf --install
@ -43,7 +43,7 @@ A build system is a collection of tools and utilities that automate the process
make install make install
``` ```
4. **SCons**: This build system uses Python for build scripts, making it more expressive than GNU Make. It can also build for multiple platforms and configurations simultaneously. - **SCons**: This build system uses Python for build scripts, making it more expressive than GNU Make. It can also build for multiple platforms and configurations simultaneously.
Code example: Code example:
@ -53,7 +53,7 @@ A build system is a collection of tools and utilities that automate the process
env.Program(target="HelloWorld", source=["main.cpp"]) env.Program(target="HelloWorld", source=["main.cpp"])
``` ```
5. **Ninja**: A small and focused build system that takes a list of build targets specified in a human-readable text file and builds them as fast as possible. - **Ninja**: A small and focused build system that takes a list of build targets specified in a human-readable text file and builds them as fast as possible.
Code example: Code example:

@ -2,17 +2,17 @@
`vcpkg` is a cross-platform, open-source package manager for C and C++ libraries. Developed by Microsoft, it simplifies the process of acquiring and building open-source libraries for your projects. `vcpkg` supports various platforms including Windows, Linux, and macOS, enabling you to easily manage and integrate external libraries into your projects. `vcpkg` is a cross-platform, open-source package manager for C and C++ libraries. Developed by Microsoft, it simplifies the process of acquiring and building open-source libraries for your projects. `vcpkg` supports various platforms including Windows, Linux, and macOS, enabling you to easily manage and integrate external libraries into your projects.
### Installation ## Installation
To install `vcpkg`, follow these steps: To install `vcpkg`, follow these steps:
1. Clone the repository: - Clone the repository:
``` ```
git clone https://github.com/Microsoft/vcpkg.git git clone https://github.com/Microsoft/vcpkg.git
``` ```
2. Change to the `vcpkg` directory and run the bootstrap script: - Change to the `vcpkg` directory and run the bootstrap script:
- On Windows: - On Windows:
@ -26,9 +26,9 @@ To install `vcpkg`, follow these steps:
./bootstrap-vcpkg.sh ./bootstrap-vcpkg.sh
``` ```
3. (Optional) Add the `vcpkg` executable to your `PATH` environment variable for easy access. - (Optional) Add the `vcpkg` executable to your `PATH` environment variable for easy access.
### Basic usage ## Basic usage
Here are some basic examples of using `vcpkg`: Here are some basic examples of using `vcpkg`:

@ -2,16 +2,16 @@
[Spack](https://spack.io/) is a flexible package manager designed to support multiple versions, configurations, platforms, and compilers. It is particularly useful in High Performance Computing (HPC) environments and for those who require fine control over their software stack. Spack is a popular choice in scientific computing due to its support for various platforms such as Linux, macOS, and many supercomputers. It is designed to automatically search for and install dependencies, making it easy to build complex software. [Spack](https://spack.io/) is a flexible package manager designed to support multiple versions, configurations, platforms, and compilers. It is particularly useful in High Performance Computing (HPC) environments and for those who require fine control over their software stack. Spack is a popular choice in scientific computing due to its support for various platforms such as Linux, macOS, and many supercomputers. It is designed to automatically search for and install dependencies, making it easy to build complex software.
### Key Features ## Key Features
- **Multi-Version Support**: Spack allows for the installation of multiple versions of packages, enabling users to work with different configurations depending on their needs. - **Multi-Version Support**: Spack allows for the installation of multiple versions of packages, enabling users to work with different configurations depending on their needs.
- **Compiler Support**: Spack supports multiple compilers, including GCC, Clang, Intel, PGI, and others, allowing users to choose the best toolchain for their application. - **Compiler Support**: Spack supports multiple compilers, including GCC, Clang, Intel, PGI, and others, allowing users to choose the best toolchain for their application.
- **Platform Support**: Spack can run on Linux, macOS, and various supercomputers, and it can even target multiple architectures within a single package. - **Platform Support**: Spack can run on Linux, macOS, and various supercomputers, and it can even target multiple architectures within a single package.
- **Dependencies**: Spack takes care of dependencies, providing automatic installation and management of required packages. - **Dependencies**: Spack takes care of dependencies, providing automatic installation and management of required packages.
### Basic Usage ## Basic Usage
1. To install Spack, clone its Git repository and set up your environment: - To install Spack, clone its Git repository and set up your environment:
```bash ```bash
git clone https://github.com/spack/spack.git git clone https://github.com/spack/spack.git
@ -19,7 +19,7 @@
. share/spack/setup-env.sh . share/spack/setup-env.sh
``` ```
2. Install a package using Spack: - Install a package using Spack:
```bash ```bash
spack install <package-name> spack install <package-name>
@ -31,7 +31,7 @@
spack install hdf5 spack install hdf5
``` ```
3. Load a package in your environment: - Load a package in your environment:
```bash ```bash
spack load <package-name> spack load <package-name>
@ -43,13 +43,13 @@
spack load hdf5 spack load hdf5
``` ```
4. List installed packages: - List installed packages:
```bash ```bash
spack find spack find
``` ```
5. Uninstall a package: - Uninstall a package:
```bash ```bash
spack uninstall <package-name> spack uninstall <package-name>

@ -2,7 +2,7 @@
[Conan](https://conan.io/) is a popular package manager for C and C++ languages and is designed to be cross-platform, extensible, and easy to use. It allows developers to declare, manage, and fetch dependencies while automating the build process. Conan supports various build systems, such as CMake, Visual Studio, MSBuild, and more. [Conan](https://conan.io/) is a popular package manager for C and C++ languages and is designed to be cross-platform, extensible, and easy to use. It allows developers to declare, manage, and fetch dependencies while automating the build process. Conan supports various build systems, such as CMake, Visual Studio, MSBuild, and more.
### Installation ## Installation
To install Conan, you can use pip, the Python package manager: To install Conan, you can use pip, the Python package manager:
@ -10,9 +10,9 @@ To install Conan, you can use pip, the Python package manager:
pip install conan pip install conan
``` ```
### Basic Usage ## Basic Usage
1. Create a `conanfile.txt` file in your project root directory, specifying dependencies you need for your project: - Create a `conanfile.txt` file in your project root directory, specifying dependencies you need for your project:
```ini ```ini
[requires] [requires]
@ -22,21 +22,21 @@ boost/1.75.0
cmake cmake
``` ```
2. Run the `conan install` command to fetch and build required dependencies: - Run the `conan install` command to fetch and build required dependencies:
```bash ```bash
mkdir build && cd build mkdir build && cd build
conan install .. conan install ..
``` ```
3. Now build your project using your build system, for example CMake: - Now build your project using your build system, for example CMake:
```bash ```bash
cmake .. -DCMAKE_BUILD_TYPE=Release cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . cmake --build .
``` ```
### Creating Packages ## Creating Packages
To create a package in Conan, you need to write a `conanfile.py` file with package information and build instructions. To create a package in Conan, you need to write a `conanfile.py` file with package information and build instructions.

@ -2,18 +2,18 @@
[NuGet](https://www.nuget.org/) is a Microsoft-supported package manager for the .NET framework, mainly used in C# and other .NET languages, but also supports C++ projects with `PackageReference`. It allows you to easily add, update, and manage dependencies in your projects. [NuGet](https://www.nuget.org/) is a Microsoft-supported package manager for the .NET framework, mainly used in C# and other .NET languages, but also supports C++ projects with `PackageReference`. It allows you to easily add, update, and manage dependencies in your projects.
#### Installation ### Installation
You can use NuGet either as a command-line tool or integrated in your preferred IDE like Visual Studio or Visual Studio Code. If you're using Visual Studio, it comes pre-installed. For other editors, you may need to download the command-line tool `nuget.exe`. You can use NuGet either as a command-line tool or integrated in your preferred IDE like Visual Studio or Visual Studio Code. If you're using Visual Studio, it comes pre-installed. For other editors, you may need to download the command-line tool `nuget.exe`.
#### Usage ### Usage
You can use NuGet to manage your C++ dependencies using the PackageReference format in vcxproj files: You can use NuGet to manage your C++ dependencies using the PackageReference format in vcxproj files:
1. Tools > NuGet Package Manager > Manage NuGet Packages for Solution… - Tools > NuGet Package Manager > Manage NuGet Packages for Solution…
2. Package source should be set to "nuget.org" - Package source should be set to "nuget.org"
3. Select the Projects tab - Select the Projects tab
4. Use the search box to find packages - Use the search box to find packages
For example, to install a package called "PackageName" for all configurations: For example, to install a package called "PackageName" for all configurations:
@ -26,7 +26,7 @@ For example, to install a package called "PackageName" for all configurations:
</Project> </Project>
``` ```
#### NuGet Command-Line ### NuGet Command-Line
You can also use the command-line tool `nuget.exe` for more advanced scenarios or for specific needs. You can also use the command-line tool `nuget.exe` for more advanced scenarios or for specific needs.

@ -4,11 +4,11 @@ Package managers are tools that automate the process of installing, upgrading, a
Some popular package managers used in the C++ ecosystem include: Some popular package managers used in the C++ ecosystem include:
1. **Conan** - **Conan**
2. **vcpkg** - **vcpkg**
3. **C++ Archive Network (cppan)** - **C++ Archive Network (cppan)**
### Conan ## Conan
[Conan](https://conan.io/) is an open-source, decentralized, cross-platform package manager for C and C++ developers. It simplifies managing dependencies and reusing code, which benefits multi-platform development projects. [Conan](https://conan.io/) is an open-source, decentralized, cross-platform package manager for C and C++ developers. It simplifies managing dependencies and reusing code, which benefits multi-platform development projects.
@ -18,7 +18,7 @@ For example, installing a library using Conan:
conan install poco/1.9.4@ conan install poco/1.9.4@
``` ```
### vcpkg ## vcpkg
[vcpkg](https://github.com/microsoft/vcpkg) is a cross-platform package manager created by Microsoft. It is an open-source library management system for C++ developers to build and manage their projects. [vcpkg](https://github.com/microsoft/vcpkg) is a cross-platform package manager created by Microsoft. It is an open-source library management system for C++ developers to build and manage their projects.
@ -28,7 +28,7 @@ For example, installing a package using vcpkg:
./vcpkg install boost:x64-windows ./vcpkg install boost:x64-windows
``` ```
### C++ Archive Network (cppan) ##C++ Archive Network (cppan)
[cppan](https://cppan.org/) is a package manager and software repository for C++ developers, simplifying the process of managing and distributing C++ libraries and tools. It's now part of [build2](https://build2.org/), a build toolchain that provides a package manager. [cppan](https://cppan.org/) is a package manager and software repository for C++ developers, simplifying the process of managing and distributing C++ libraries and tools. It's now part of [build2](https://build2.org/), a build toolchain that provides a package manager.

@ -2,10 +2,10 @@
In C++ programming, inclusion refers to incorporating external libraries, header files, or other code files into your program. This process allows developers to access pre-built functions, classes, and variable declarations that can be used in their own code. There are two types of inclusion in C++: In C++ programming, inclusion refers to incorporating external libraries, header files, or other code files into your program. This process allows developers to access pre-built functions, classes, and variable declarations that can be used in their own code. There are two types of inclusion in C++:
1. Header Inclusion - Header Inclusion
2. Source Inclusion - Source Inclusion
#### Header Inclusion ### Header Inclusion
Header inclusion involves including header files using the preprocessor directive `#include`. Header files are typically used to provide function prototypes, class declarations, and constant definitions that can be shared across multiple source files. There are two ways to include header files in your program: Header inclusion involves including header files using the preprocessor directive `#include`. Header files are typically used to provide function prototypes, class declarations, and constant definitions that can be shared across multiple source files. There are two ways to include header files in your program:
@ -25,7 +25,7 @@ Example:
#include "thirdPartyLibrary.h" #include "thirdPartyLibrary.h"
``` ```
#### Source Inclusion ### Source Inclusion
Source inclusion refers to including the content of a source file directly in another source file. This approach is generally not recommended as it can lead to multiple definitions and increased compile times but it can occasionally be useful for certain tasks (e.g., templates or simple small programs). To include a source file, you can use the `#include` directive with double quotes, just like with header files: Source inclusion refers to including the content of a source file directly in another source file. This approach is generally not recommended as it can lead to multiple definitions and increased compile times but it can occasionally be useful for certain tasks (e.g., templates or simple small programs). To include a source file, you can use the `#include` directive with double quotes, just like with header files:

@ -2,7 +2,7 @@
Licensing is a crucial aspect of working with libraries in C++ because it determines the rights and limitations on how you can use, modify, and distribute a given library. There are various types of licenses applied to open-source libraries. Below is a brief overview of three common licenses: Licensing is a crucial aspect of working with libraries in C++ because it determines the rights and limitations on how you can use, modify, and distribute a given library. There are various types of licenses applied to open-source libraries. Below is a brief overview of three common licenses:
#### 1. MIT License ## MIT License
The MIT License is a permissive license that allows users to do whatever they want with the software code. They only need to include the original copyright, license notice, and a disclaimer of warranty in their copies. The MIT License is a permissive license that allows users to do whatever they want with the software code. They only need to include the original copyright, license notice, and a disclaimer of warranty in their copies.
@ -14,7 +14,7 @@ Example: Including the MIT License into your project can be done by simply addin
*/ */
``` ```
#### 2. GNU General Public License (GPL) ## GNU General Public License (GPL)
The GPL is a copyleft license that grants users the rights to use, study, share, and modify the software code. However, any changes made to the code or any software that uses GPL licensed code must also be distributed under the GPL license. The GPL is a copyleft license that grants users the rights to use, study, share, and modify the software code. However, any changes made to the code or any software that uses GPL licensed code must also be distributed under the GPL license.
Example: To include a GPL license in your project, include a `COPYING` file with the full text of the license and place a notice in your source code files like: Example: To include a GPL license in your project, include a `COPYING` file with the full text of the license and place a notice in your source code files like:
@ -25,7 +25,7 @@ Example: To include a GPL license in your project, include a `COPYING` file with
*/ */
``` ```
#### 3. Apache License 2.0 ## Apache License 2.0
The Apache License is a permissive license similar to the MIT license and allows users to do virtually anything with the software code. The primary difference is that it requires that any changes to the code are documented, and it provides specific terms for patent protection. The Apache License is a permissive license similar to the MIT license and allows users to do virtually anything with the software code. The primary difference is that it requires that any changes to the code are documented, and it provides specific terms for patent protection.
Example: To include the Apache License in your project, add a `LICENSE` file with the full text of the license. Add a notice to your source code files like: Example: To include the Apache License in your project, add a `LICENSE` file with the full text of the license. Add a notice to your source code files like:

@ -2,24 +2,24 @@
Google Test, also known as gtest or googletest, is a C++ testing framework developed by Google. It provides a user-friendly API for writing test cases and is designed for use in a range of applications, from simple unit tests to complex system-level tests. Google Test, also known as gtest or googletest, is a C++ testing framework developed by Google. It provides a user-friendly API for writing test cases and is designed for use in a range of applications, from simple unit tests to complex system-level tests.
### Getting Started with Google Test ## Getting Started with Google Test
To use Google Test in your project, follow these steps: To use Google Test in your project, follow these steps:
1. Download the source code from the [GoogleTest GitHub repository](https://github.com/google/googletest). - Download the source code from the [GoogleTest GitHub repository](https://github.com/google/googletest).
2. Build and install Google Test on your system. Instructions for various platforms can be found in the [README](https://github.com/google/googletest/blob/master/googletest/README.md) file. - Build and install Google Test on your system. Instructions for various platforms can be found in the [README](https://github.com/google/googletest/blob/master/googletest/README.md) file.
3. Include the necessary headers and link against the Google Test library in your project. - Include the necessary headers and link against the Google Test library in your project.
### Writing a Test with Google Test ## Writing a Test with Google Test
Here's an example of how to write a simple test using Google Test: Here's an example of how to write a simple test using Google Test:
1. **Include the necessary headers** - **Include the necessary headers**
```cpp ```cpp
#include "gtest/gtest.h" #include "gtest/gtest.h"
``` ```
2. **Write the functions you want to test** - **Write the functions you want to test**
Suppose we have a simple function to test: Suppose we have a simple function to test:
```cpp ```cpp
@ -28,7 +28,7 @@ Here's an example of how to write a simple test using Google Test:
} }
``` ```
3. **Write the test cases** - **Write the test cases**
To create a test case, use the `TEST()` macro, which takes two arguments: the test suite name and the test case name. To create a test case, use the `TEST()` macro, which takes two arguments: the test suite name and the test case name.
@ -45,7 +45,7 @@ Here's an example of how to write a simple test using Google Test:
} }
``` ```
4. **Write a `main()` function** - **Write a `main()` function**
In order to run the tests, include a `main()` function that initializes Google Test and runs the tests. In order to run the tests, include a `main()` function that initializes Google Test and runs the tests.
@ -56,11 +56,11 @@ Here's an example of how to write a simple test using Google Test:
} }
``` ```
5. **Compile and run the tests** - **Compile and run the tests**
Compile your test program with the Google Test library and run the test executable. Compile your test program with the Google Test library and run the test executable.
### More Features ## More Features
Google Test offers a wide range of features to make testing easier, such as: Google Test offers a wide range of features to make testing easier, such as:

@ -4,14 +4,14 @@ Qt is an open-source, cross-platform framework for creating high-performance app
Qt provides a wide range of C++ libraries and seamless integration with popular IDEs, making it easier for developers to create feature-rich applications. It offers a comprehensive development environment, including tools for designing, coding, debugging, and profiling applications. Qt provides a wide range of C++ libraries and seamless integration with popular IDEs, making it easier for developers to create feature-rich applications. It offers a comprehensive development environment, including tools for designing, coding, debugging, and profiling applications.
### Key Features ## Key Features
- **Cross-platform**: Qt can create applications that run on different platforms (e.g., Windows, macOS, Linux, Android, iOS) without any platform-specific code. - **Cross-platform**: Qt can create applications that run on different platforms (e.g., Windows, macOS, Linux, Android, iOS) without any platform-specific code.
- **Modular Libraries**: Qt consists of several modular libraries, including QtCore (core non-GUI functionality), QtGui (GUI-related classes), QtWidgets (GUI widgets), and QtNetwork (networking support). - **Modular Libraries**: Qt consists of several modular libraries, including QtCore (core non-GUI functionality), QtGui (GUI-related classes), QtWidgets (GUI widgets), and QtNetwork (networking support).
- **Signals and Slots**: Qt provides a unique mechanism to handle events called "signals and slots", which allows safe and flexible inter-object communication. - **Signals and Slots**: Qt provides a unique mechanism to handle events called "signals and slots", which allows safe and flexible inter-object communication.
- **OpenGL Integration**: Qt supports rendering 2D and 3D graphics using OpenGL, making it suitable for game development and other graphical applications. - **OpenGL Integration**: Qt supports rendering 2D and 3D graphics using OpenGL, making it suitable for game development and other graphical applications.
### Code Example ## Code Example
Here's a simple example of a "Hello, World!" application using Qt: Here's a simple example of a "Hello, World!" application using Qt:

@ -13,7 +13,7 @@ Catch2 is a modern, C++-native, test framework for unit tests, TDD, and BDD. It
## Code examples ## Code examples
### Basic test case ## Basic test case
```cpp ```cpp
#define CATCH_CONFIG_MAIN // Tells Catch to provide a main() function #define CATCH_CONFIG_MAIN // Tells Catch to provide a main() function
@ -28,7 +28,7 @@ TEST_CASE("Addition") {
} }
``` ```
### Sections ## Sections
```cpp ```cpp
TEST_CASE("Sections example") { TEST_CASE("Sections example") {
@ -46,7 +46,7 @@ TEST_CASE("Sections example") {
} }
``` ```
### BDD style ## BDD style
```cpp ```cpp
SCENARIO("vector can be sized and resized", "[vector]") { SCENARIO("vector can be sized and resized", "[vector]") {
@ -81,7 +81,7 @@ SCENARIO("vector can be sized and resized", "[vector]") {
} }
``` ```
### Matchers ## Matchers
```cpp ```cpp
TEST_CASE("Matchers example") { TEST_CASE("Matchers example") {

@ -9,15 +9,15 @@ Orbit Profiler is a performance profiler for C++ applications. It is designed to
- Callstacks collection - Callstacks collection
- Frame-based measurements using scopes macros - Frame-based measurements using scopes macros
### Usage ## Usage
1. **Include OrbitProfiler.h**: First, you need to include the `OrbitProfiler.h` header file in your project: - **Include OrbitProfiler.h**: First, you need to include the `OrbitProfiler.h` header file in your project:
```cpp ```cpp
#include "OrbitProfiler.h" #include "OrbitProfiler.h"
``` ```
2. **Starting and Stopping the profiler**: Use `ORBET_START` and `ORBIT_STOP` to start and stop the profiler. - **Starting and Stopping the profiler**: Use `ORBET_START` and `ORBIT_STOP` to start and stop the profiler.
```cpp ```cpp
ORBIT_START(); ORBIT_START();
@ -25,7 +25,7 @@ Orbit Profiler is a performance profiler for C++ applications. It is designed to
ORBIT_STOP(); ORBIT_STOP();
``` ```
3. **Instrumenting scopes**: Use the `ORBET_SCOPE` macro to annotate the scope of the function you want to measure: - **Instrumenting scopes**: Use the `ORBET_SCOPE` macro to annotate the scope of the function you want to measure:
```cpp ```cpp
void ExampleFunction() { void ExampleFunction() {
@ -34,9 +34,9 @@ Orbit Profiler is a performance profiler for C++ applications. It is designed to
} }
``` ```
4. **Visualizing the captured data**: Orbit Profiler provides a **Session View** that displays the captured data and allows you to navigate through the timeline, analyze data, and identify performance bottlenecks. - **Visualizing the captured data**: Orbit Profiler provides a **Session View** that displays the captured data and allows you to navigate through the timeline, analyze data, and identify performance bottlenecks.
### Example ## Example
For demonstration purposes, consider the following example of a simple C++ application: For demonstration purposes, consider the following example of a simple C++ application:

@ -2,11 +2,11 @@
PyTorch C++ is the C++ API (Application Programming Interface) for PyTorch. It is also known as LibTorch, which is a library that provides almost all the functionality of PyTorch accessible through C++ language. The main goal of providing a C++ API is to enable high-performance integration with other deep learning platforms and enable seamless operation in enterprise and production-level systems. PyTorch C++ is the C++ API (Application Programming Interface) for PyTorch. It is also known as LibTorch, which is a library that provides almost all the functionality of PyTorch accessible through C++ language. The main goal of providing a C++ API is to enable high-performance integration with other deep learning platforms and enable seamless operation in enterprise and production-level systems.
### Installation ## Installation
To use the PyTorch C++ API, you need to install the LibTorch distribution. Follow the instructions on the [official PyTorch C++ API page](https://pytorch.org/cppdocs/installing.html) to install the library based on your platform and requirements. To use the PyTorch C++ API, you need to install the LibTorch distribution. Follow the instructions on the [official PyTorch C++ API page](https://pytorch.org/cppdocs/installing.html) to install the library based on your platform and requirements.
### Example: Tensors ## Example: Tensors
```cpp ```cpp
#include <iostream> #include <iostream>
@ -31,7 +31,7 @@ int main() {
} }
``` ```
### Example: Creating a Custom Module ## Example: Creating a Custom Module
```cpp ```cpp
#include <iostream> #include <iostream>

@ -14,8 +14,8 @@ Here's a list of some popular Boost libraries:
## Usage ## Usage
1. First, download and install the Boost libraries according to the [documentation](https://www.boost.org/doc/libs/1_76_0/more/getting_started/index.html). - First, download and install the Boost libraries according to the [documentation](https://www.boost.org/doc/libs/1_76_0/more/getting_started/index.html).
2. After installation, include necessary headers in your C++ code and start using Boost facilities. - After installation, include necessary headers in your C++ code and start using Boost facilities.
Here's an example using `boost::filesystem` (*NOTE: Boost.Filesystem is now part of the C++17 standard library*): Here's an example using `boost::filesystem` (*NOTE: Boost.Filesystem is now part of the C++17 standard library*):

@ -2,7 +2,7 @@
Poco (also known as POCO C++ Libraries) is a collection of open-source class libraries, which simplifies the creation of network-centric, portable, and maintainable software in C++. Poco (also known as POCO C++ Libraries) is a collection of open-source class libraries, which simplifies the creation of network-centric, portable, and maintainable software in C++.
### Overview ## Overview
Poco library provides functionality for various areas, such as: Poco library provides functionality for various areas, such as:
@ -13,7 +13,7 @@ Poco library provides functionality for various areas, such as:
- Data manipulation: Stream, ByteBuffer, Buffer, etc. - Data manipulation: Stream, ByteBuffer, Buffer, etc.
- Multithreading and synchronization: Threads, Mutex, Event, and Condition - Multithreading and synchronization: Threads, Mutex, Event, and Condition
### Code Example ## Code Example
Here's an example demonstrating an HTTP client using the Poco library: Here's an example demonstrating an HTTP client using the Poco library:

@ -4,7 +4,7 @@ Protocol Buffers, or protobuf, is a language and platform-neutral data serializa
Here is a brief summary of protobuf and how to use it in C++: Here is a brief summary of protobuf and how to use it in C++:
1. **Define your `.proto` file:** Create a `.proto` file that defines the structure of your messages. - **Define your `.proto` file:** Create a `.proto` file that defines the structure of your messages.
*Example:* *Example:*
@ -18,7 +18,7 @@ Here is a brief summary of protobuf and how to use it in C++:
} }
``` ```
2. **Compile the `.proto` file:** You need to compile your `.proto` file to generate C++ classes for serialization and deserialization. - **Compile the `.proto` file:** You need to compile your `.proto` file to generate C++ classes for serialization and deserialization.
*Example:* *Example:*
@ -28,7 +28,7 @@ Here is a brief summary of protobuf and how to use it in C++:
This will generate two files: `person.pb.cc` and `person.pb.h` that contains the C++ class definitions. This will generate two files: `person.pb.cc` and `person.pb.h` that contains the C++ class definitions.
3. **Include protobuf library and generated files into your C++ code:** You'll need to include the protobuf library and the generated files in your main C++ code. - **Include protobuf library and generated files into your C++ code:** You'll need to include the protobuf library and the generated files in your main C++ code.
*Example:* *Example:*
@ -68,7 +68,7 @@ Here is a brief summary of protobuf and how to use it in C++:
} }
``` ```
4. **Compile and link your C++ code:** Finally, compile your C++ code and link it to the protobuf library. - **Compile and link your C++ code:** Finally, compile your C++ code and link it to the protobuf library.
*Example:* *Example:*

@ -4,7 +4,7 @@ gRPC (gRPC Remote Procedure Calls) is an open-source Remote Procedure Call (RPC)
gRPC uses the Protocol Buffers (Protobuf) serialization format for message exchange and method definition. Protocol Buffers enable more efficient and smaller serialization compared to other formats like JSON or XML. gRPC uses the Protocol Buffers (Protobuf) serialization format for message exchange and method definition. Protocol Buffers enable more efficient and smaller serialization compared to other formats like JSON or XML.
### Protocol Buffers ## Protocol Buffers
In gRPC, you start by defining service definitions and message structures in `.proto` files. You can define data structures and service interfaces using a compact, language-neutral, platform-neutral binary format. In gRPC, you start by defining service definitions and message structures in `.proto` files. You can define data structures and service interfaces using a compact, language-neutral, platform-neutral binary format.
@ -33,7 +33,7 @@ message HelloReply {
After defining the `.proto` file, you use the `protoc` compiler to generate the corresponding C++ code for your application. After defining the `.proto` file, you use the `protoc` compiler to generate the corresponding C++ code for your application.
### gRPC C++ Server ## gRPC C++ Server
To create a gRPC server in C++, you first need to implement the service interface generated by the `protoc` compiler. Here's an example implementation for the `Greeter` service: To create a gRPC server in C++, you first need to implement the service interface generated by the `protoc` compiler. Here's an example implementation for the `Greeter` service:
@ -76,7 +76,7 @@ int main(int argc, char** argv) {
} }
``` ```
### gRPC C++ Client ## gRPC C++ Client
Similarly, to create a gRPC C++ client, you use the generated code from `protoc` compiler and connect to a server: Similarly, to create a gRPC C++ client, you use the generated code from `protoc` compiler and connect to a server:

@ -4,7 +4,7 @@ Pybind11 is a lightweight header-only library that seamlessly integrates C++ cod
Pybind11 helps in creating library extensions, bringing high-performance C++ code into Python programs, and using Python's flexibility for rapid development while still benefiting from the efficiency of C++. Pybind11 helps in creating library extensions, bringing high-performance C++ code into Python programs, and using Python's flexibility for rapid development while still benefiting from the efficiency of C++.
#### Code Examples ### Code Examples
Here are a few examples of Pybind11 for understanding the concept better: Here are a few examples of Pybind11 for understanding the concept better:

@ -2,14 +2,14 @@
`spdlog` is a fast, header-only, C++ logging library. It provides a simple and efficient way to add diagnostic logging to your C++ application. `spdlog` is a fast, header-only, C++ logging library. It provides a simple and efficient way to add diagnostic logging to your C++ application.
### Features: ## Features:
- Header-only, no need to build or link a library - Header-only, no need to build or link a library
- Highly configurable, including support for custom log sinks (e.g. writing to a file or a database) - Highly configurable, including support for custom log sinks (e.g. writing to a file or a database)
- Asynchronous and synchronous logging modes - Asynchronous and synchronous logging modes
- Preprocessor-based format string checks to catch bugs at compile-time - Preprocessor-based format string checks to catch bugs at compile-time
- Easy to extend with custom formatters, sinks, and levels - Easy to extend with custom formatters, sinks, and levels
### Usage example: ## Usage example:
Include the `spdlog` header, create a logger object, and use it to log messages: Include the `spdlog` header, create a logger object, and use it to log messages:
@ -29,7 +29,7 @@ int main() {
} }
``` ```
### Custom sink example: ## Custom sink example:
Here's an example of creating a logger with a custom sink that writes to a text file: Here's an example of creating a logger with a custom sink that writes to a text file:

@ -2,19 +2,19 @@
OpenCL (Open Computing Language) is a framework for writing programs that enables you to execute code on heterogeneous platforms consisting of CPUs, GPUs, and other processors. It is primarily used for parallel programming, and it can be employed to improve the performance of various applications, including gaming, image and video rendering, and scientific computing. OpenCL (Open Computing Language) is a framework for writing programs that enables you to execute code on heterogeneous platforms consisting of CPUs, GPUs, and other processors. It is primarily used for parallel programming, and it can be employed to improve the performance of various applications, including gaming, image and video rendering, and scientific computing.
### Overview ## Overview
OpenCL provides a standardized programming interface, allowing you to target different devices such as graphics cards from different vendors. You can program in C with OpenCL C or C++ with OpenCL C++ kernel language, which are based on the ISO C99 and C++14 respectively, with specific extensions, built-ins, and features to exploit device parallelism. OpenCL provides a standardized programming interface, allowing you to target different devices such as graphics cards from different vendors. You can program in C with OpenCL C or C++ with OpenCL C++ kernel language, which are based on the ISO C99 and C++14 respectively, with specific extensions, built-ins, and features to exploit device parallelism.
### Key Concepts ## Key Concepts
1. Platform: A collection of devices and software features provided by a vendor. - Platform: A collection of devices and software features provided by a vendor.
2. Device: A processing unit that can execute OpenCL code, e.g., a CPU or a GPU. - Device: A processing unit that can execute OpenCL code, e.g., a CPU or a GPU.
3. Command queue: A sequence of instructions to be executed on a device. - Command queue: A sequence of instructions to be executed on a device.
4. Kernel: A parallelized function that is executed on OpenCL devices. - Kernel: A parallelized function that is executed on OpenCL devices.
5. Buffer: A memory object that stores a specific amount of data (e.g., an array of integers or floats) that is accessible by both the host and devices. - Buffer: A memory object that stores a specific amount of data (e.g., an array of integers or floats) that is accessible by both the host and devices.
### Sample Code ## Sample Code
Here is a simple OpenCL code example that illustrates how to implement vector addition: Here is a simple OpenCL code example that illustrates how to implement vector addition:

@ -13,7 +13,7 @@
Here are some examples of how to use the `fmt` library: Here are some examples of how to use the `fmt` library:
### Basic Usage ## Basic Usage
```cpp ```cpp
#include <fmt/core.h> #include <fmt/core.h>
@ -24,7 +24,7 @@ int main() {
} }
``` ```
### Formatting with Positional Arguments ## Formatting with Positional Arguments
```cpp ```cpp
#include <fmt/core.h> #include <fmt/core.h>
@ -36,7 +36,7 @@ int main() {
} }
``` ```
### Formatting with Named Arguments ## Formatting with Named Arguments
```cpp ```cpp
#include <fmt/core.h> #include <fmt/core.h>
@ -47,7 +47,7 @@ int main() {
} }
``` ```
### Using Format String Syntax ## Using Format String Syntax
```cpp ```cpp
#include <fmt/core.h> #include <fmt/core.h>

@ -8,11 +8,11 @@ Ranges v3 is a C++ library designed to work with ranges of values, rather than i
Ranges v3 includes three main components: Ranges v3 includes three main components:
1. **Range adaptors:** These are composable algorithms that transform a range into a new range. They help to create lazy views over the data without actually modifying it. - **Range adaptors:** These are composable algorithms that transform a range into a new range. They help to create lazy views over the data without actually modifying it.
2. **Action adaptors:** These are algorithms that modify a range in-place. For example, sorting or filtering elements in a container directly. - **Action adaptors:** These are algorithms that modify a range in-place. For example, sorting or filtering elements in a container directly.
3. **Trait concepts and utility functions:** Provide tools for working with range types, like determining if a type is a range, getting the iterator type for a range, etc. - **Trait concepts and utility functions:** Provide tools for working with range types, like determining if a type is a range, getting the iterator type for a range, etc.
--- ---
@ -20,7 +20,7 @@ Ranges v3 includes three main components:
Here are some code examples of using the Ranges v3 library: Here are some code examples of using the Ranges v3 library:
### Including the library ## Including the library
First, you need to include the appropriate header files from the library. To use the entire Ranges v3 library, you can simply include the `range/v3/all.hpp` header file: First, you need to include the appropriate header files from the library. To use the entire Ranges v3 library, you can simply include the `range/v3/all.hpp` header file:
@ -28,7 +28,7 @@ First, you need to include the appropriate header files from the library. To use
#include <range/v3/all.hpp> #include <range/v3/all.hpp>
``` ```
### Using range adaptors ## Using range adaptors
You can use range adaptors to manipulate and transform ranges. For example, you can use the `view::filter` and `view::transform` adaptors to create a new range containing only even numbers and then square them: You can use range adaptors to manipulate and transform ranges. For example, you can use the `view::filter` and `view::transform` adaptors to create a new range containing only even numbers and then square them:
@ -55,7 +55,7 @@ int main() {
} }
``` ```
### Using action adaptors ## Using action adaptors
Action adaptors are used to modify ranges in-place. For example, you can use the `action::sort` and `action::unique` adaptors to sort and remove duplicate elements from a container: Action adaptors are used to modify ranges in-place. For example, you can use the `action::sort` and `action::unique` adaptors to sort and remove duplicate elements from a container:

Loading…
Cancel
Save