{"id":17117600,"url":"https://github.com/utkuufuk/cpp-quick-reference","last_synced_at":"2025-10-10T13:37:11.796Z","repository":{"id":107371495,"uuid":"89881420","full_name":"utkuufuk/cpp-quick-reference","owner":"utkuufuk","description":"C++ Quick Reference","archived":false,"fork":false,"pushed_at":"2020-10-01T03:09:42.000Z","size":853,"stargazers_count":183,"open_issues_count":0,"forks_count":24,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-13T03:30:14.743Z","etag":null,"topics":["c-plus-plus","cpp","guide","language-learning","reference","tutorial"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/utkuufuk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-04-30T22:36:28.000Z","updated_at":"2025-01-26T10:42:57.000Z","dependencies_parsed_at":null,"dependency_job_id":"536e0d5d-9c56-4c28-9361-d161b5c2b8f0","html_url":"https://github.com/utkuufuk/cpp-quick-reference","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/utkuufuk/cpp-quick-reference","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkuufuk%2Fcpp-quick-reference","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkuufuk%2Fcpp-quick-reference/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkuufuk%2Fcpp-quick-reference/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkuufuk%2Fcpp-quick-reference/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/utkuufuk","download_url":"https://codeload.github.com/utkuufuk/cpp-quick-reference/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkuufuk%2Fcpp-quick-reference/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264697567,"owners_count":23650955,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-plus-plus","cpp","guide","language-learning","reference","tutorial"],"created_at":"2024-10-14T17:52:11.391Z","updated_at":"2025-10-10T13:37:06.759Z","avatar_url":"https://github.com/utkuufuk.png","language":"C++","readme":"# C++ Quick Reference\n\n 1. [Namespaces](#1-namespaces)\n 2. [Memory Management](#2-memory-management)\u003cbr\u003e\n    2.1. [Raw Pointers](#21-raw-pointers)\u003cbr\u003e\n    2.2. [Smart Pointers](#22-smart-pointers)\u003cbr\u003e\n    2.3. [References](#23-references)\n 3. [Characters \u0026 Strings](#3-characters-and-strings)\u003cbr\u003e\n    3.1. [Character Functions](#31-character-functions)\u003cbr\u003e\n    3.2. [C-String Functions](#32-c-string-functions)\u003cbr\u003e\n    3.3. [Strings](#33-strings)\n 4. [Data Structures](#4-data-structures)\u003cbr\u003e\n    4.1. [Vectors](#41-vectors)\u003cbr\u003e\n    4.2. [Maps](#42-maps)\n 5. [Structs \u0026 Classes](#5-structs-and-classes)\u003cbr\u003e\n    5.1. [Structs](#51-structs)\u003cbr\u003e\n    5.2. [Classes](#52-classes)\u003cbr\u003e\n    5.3. [Inheritance](#53-inheritance)\u003cbr\u003e\n    5.4. [Enumerated Data Types](#54-enumerated-data-types)\n 6. [Templates](#6-templates)\u003cbr\u003e\n    6.1. [Function Templates](#61-function-templates)\u003cbr\u003e\n    6.2. [Class Templates](#62-class-templates)\n 7. [File Operations](#7-file-operations)\n 8. [Exceptions](#8-exceptions)\n 9. [Operator Overloading](#9-operator-overloading)\n 10. [`auto` Keyword](#10-auto-keyword)\n\n## 1. Namespaces\n\nNamespaces provide a method for preventing name conflicts in large projects.\n\nSymbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.\n\nMultiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.\n\n```cpp\n// this line should not be put in headers because it defeats the purpose of using namespaces\nusing namespace std;\n```\n\nThe line above allows you to directly use use functions \u0026 variables from `std` namespace:\n\n```cpp\ncout \u003c\u003c \"Hello world.\" \u003c\u003c endl;\n```\n\nas opposed to:\n\n```cpp\nstd::cout \u003c\u003c \"Hello world.\" \u003c\u003c std::endl;\n```\n\nOn the other hand, the following lets you use only `cout` \u0026 `endl` directly from `std:`\n\n```cpp\nusing std::cout;\nusing std::endl;\n```\n\n#### Example\n\n```cpp\n#include \u003ciostream\u003e\n\nnamespace first\n{\n    int getVal()\n    {\n        return 5;\n    }\n}\n\nnamespace second\n{\n    const double x = 100;\n\n    double getVal()\n    {\n        return 2 * x;\n    }\n}\n\nusing namespace std;\nusing second::x;\n\nint main()\n{\n    // access function within first\n    cout \u003c\u003c first::getVal() \u003c\u003c endl;\n\n    // access function within second\n    cout \u003c\u003c second::getVal() \u003c\u003c endl;\n\n    // access variable x directly\n    cout \u003c\u003c x \u003c\u003c endl;\n}\n```\n\n#### Declarations \u0026 Definitions in Namespaces\n\n```cpp\nnamespace Q\n{\n    // V is a member of Q, and is fully defined within Q\n    namespace V\n    {\n        // C is a member of V and is fully defined within V\n        class C\n        {\n            // C::m is only declared\n            void m();\n        };\n\n        // f is a member of V, but is only declared here\n        void f();\n    }\n\n    // definition of V's member f outside of V\n    // f's enclosing namespaces are still the global namespace, Q, and Q::V\n    void V::f()\n    {\n        // This declares ::Q::V::h\n        extern void h();\n    }\n\n    // definition of V::C::m outside of the namespace (and the class body)\n    // enclosing namespaces are the global namespace, Q, and Q::V\n    void V::C::m()\n    {\n    }\n}\n```\n\n#### Anonymous Namespaces\n\nYou can define anonymous namespaces to hide variables, types and functions from the end user. Anonymous namespaces are available only in their translation unit.\n\nAs an example, check out the [header](code/multiply.h) and [implementation](code/multiply.cpp) files of the `multiply` namespace which can be used as follows:\n\n```cpp\n#include \u003ciostream\u003e\n#include \"multiply.h\"\n\nint main(int argc, char **argv)\n{\n    std::cout \u003c\u003c multiply::getFirst();      // OK\n    std::cout \u003c\u003c multiply::getProduct();    // OK\n    std::cout \u003c\u003c multiply::calc(3, 6);      // ERROR: 'calc' is not a member of 'multiply'\n    std::cout \u003c\u003c multiply::first;           // ERROR: 'first' is not a member of 'multiply'\n}\n```\n\n## 2. Memory Management\n\nKeywords `new` and `delete` in C++ replace `malloc` and `free` in C, with the exception that `new` and `delete` call the constructor and destructor as well.\n\n#### Primitive Values\n\n```cpp\nint x = 5;                      // create an int on the stack\n                                // automatically freed when calling function returns\n\nint* y = new int(5);            // crates an integer on the heap, has to be freed manually using 'delete'\ndelete y;                       // frees heap memory occupied by y\ny = nullptr;                    // good practice for preventing errors\n```\n\n#### Classes \u0026 Objects\n\n```cpp\nclass Person\n{\n    // constructor\n    // destructor\n    // other members\n}\n\nPerson* person = new Person();  // calls the constructor \u0026 instantiates a Person object\ndelete person;                  // calls the destructor \u0026 frees heap memory occupied by person\nperson = nullptr;\n```\n\n#### Arrays\n\n```cpp\nchar* s = new char[size];       // dynamically allocates memory for an array\ndelete [] s;                    // frees the allocated memory\ns = nullptr;\n```\n\n### 2.1. Raw Pointers\n\n```cpp\n// this function accepts a pointer to an array of constants\nvoid displayPayRates(const double* rates, int size)\n{\n    for (int count = 0; count \u003c size; count++)\n    {\n        cout \u003c\u003c rates[count] \u003c\u003c endl;\n    }\n}\n\n// constant pointers can not point to something else\nint value = 22;\nint* const ptr = \u0026value;\n\n// this is a constant pointer to a constant\nint number = 15;\nconst int* const ptr = \u0026number;\n```\n\n### 2.2. Smart Pointers\n\nSmart pointers are defined in the `std` namespace in the `\u003cmemory\u003e` header file.\n\nIn most cases, when you initialize a raw pointer or resource handle to point to an actual resource, pass the pointer to a smart pointer immediately. In modern C++, raw pointers are only used in small code blocks of limited scope, loops, or helper functions where performance is critical and there is no chance of confusion about ownership.\n\n#### Types of Smart Pointers\n\n**`unique_ptr`**\u003cbr\u003e\nAllows exactly one owner of the underlying pointer. Use as the default choice for POCO unless you know for certain that you require a `shared_ptr`. Can be moved to a new owner, but not copied or shared. The size is one pointer and it supports `rvalue` references for fast insertion and retrieval from C++ Standard Library collections.\n\n**`shared_ptr`**\u003cbr\u003e\nReference-counted smart pointer. Use when you want to assign one raw pointer to multiple owners, for example, when you return a copy of a pointer from a container but want to keep the original. The raw pointer is not deleted until all `shared_ptr` owners have gone out of scope or have otherwise given up ownership. The size is two pointers; one for the object and one for the shared control block that contains the reference count.\n\n**`weak_ptr`**\u003cbr\u003e\nSpecial-case smart pointer for use in conjunction with `shared_ptr`. Provides access to an object that is owned by one or more `shared_ptr` instances, but does not participate in reference counting. Use when you want to observe an object, but do not require it to remain alive. Required in some cases to break circular references between `shared_ptr` instances.\n\n```cpp\nvoid useRawPointer()\n{\n    // using a raw pointer\n    Song* pSong = new Song(\"Nothing on You\", \"Bruno Mars\");\n\n    // use pSong...\n\n    // don't forget to delete!\n    delete pSong;\n}\n\nvoid useSmartPointer()\n{\n    // declare a smart pointer on stack and pass it the raw pointer\n    unique_ptr\u003cSong\u003e song2(new Song(\"Nothing on You\", \"Bruno Mars\"));\n\n    // use song2...\n    string s = song2-\u003ename;\n    // ...\n\n} // song2 is deleted automatically here\n```\n\nThe smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown somewhere further up the stack.\n\nSmart pointers have their own member functions, which are accessed by using “dot” notation. For example, some C++ Standard Library smart pointers have a reset member function that releases ownership of the pointer. This is useful when you want to free the memory owned by the smart pointer before the smart pointer goes out of scope, as shown in the following example.\n\n```cpp\nclass LargeObject\n{\n    public:\n        void DoSomething() {}\n};\n\nvoid processLargeObject(const LargeObject\u0026 lo) {}\nvoid legacyLargeObjectFunction(LargeObject* lo) {};\n\nvoid smartPointerDemo()\n{\n    // create the object and pass it to a smart pointer\n    std::unique_ptr\u003cLargeObject\u003e pLarge(new LargeObject());\n\n    // call a method on the object\n    pLarge-\u003eDoSomething();\n\n    // pass a reference to a method\n    processLargeObject(*pLarge);\n\n    // pass raw pointer to a legacy API\n    legacyLargeObjectFunction(pLarge.get());\n\n    // free the memory before we exit function block\n    pLarge.reset();\n\n    // do some other work...\n}\n```\n\n### 2.3. References\n\nA reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer is also implemented by storing the address of an object.\nA reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value) with automatic indirection, i.e the compiler will apply the \\* operator for you.\n\n#### Example\n\n```cpp\n// i and j are pointers to ints\nvoid swap(int* i, int *j)\n{\n    int temp = *i; // dereference i\n    *i = *j;\n    *j = temp;\n}\n\n// have to pass pointers to a and b\nswap(\u0026a, \u0026b);\n```\n\n```cpp\n// i and j are references to ints\ninline void swap(int \u0026i, int \u0026j)\n{\n    int temp i; // no need to dereference\n    i = j;\n    j = temp;\n}\n\n// no need to pass pointers\nswap(a, b);\n```\n\n## 3. Characters and Strings\n\n### 3.1. Character Functions\n\n```cpp\n#include \u003ccctype\u003e   // required for using the functions below\n```\n\n#### Character testing\n\n| Function  | Returns true if the argument is a ...; returns 0 otherwise  |\n| :-------: | :---------------------------------------------------------- |\n| `isalpha` | letter of the alphabet.                                     |\n| `isalnum` | letter of the alphabet or a digit.                          |\n| `isdigit` | digit from 0 through 9.                                     |\n| `islower` | lowercase letter.                                           |\n| `isprint` | printable character (including a space).                    |\n| `ispunct` | printable character other than a digit, letter, or space.   |\n| `isupper` | uppercase letter. Otherwise, it returns 0.                  |\n| `isspace` | whitespace character. (`' '`, `' \\n '`, `' \\v '`, `' \\t '`) |\n\n#### Character case conversion\n\n| Function  | Description                                       |\n| :-------: | :------------------------------------------------ |\n| `toupper` | Returns the uppercase equivalent of its argument. |\n| `tolower` | Returns the lowercase equivalent of its argument. |\n\n### 3.2. C-String Functions\n\n```cpp\n#include \u003ccstring\u003e  // required for using the functions below\n```\n\n#### `strlen`\n\n```cpp\n// don't confuse the length of a string with the size of the array holding it\nchar name[] = \"banana\";\nint length = strlen(name); // length is 6\n```\n\n#### `strcat` (see also: [`strncat`](http://www.cplusplus.com/reference/cstring/strncat/))\n\n_If the array holding the first string isn't large enough to hold both strings,\n`strcat` will overflow the boundaries of the array._\n\n```cpp\nchar string1[100] = \"Hello \";   // string1 has enough capacity for strcat\nchar string2[] = \"World!\";\nstrcat(string1, string2);\ncout \u003c\u003c string1 \u003c\u003c endl;        // outputs \"Hello World!\"\n```\n\n#### `strcpy` (see also: [`strncpy`](http://www.cplusplus.com/reference/cstring/strncpy/))\n\n_`strcpy` performs no bounds checking. The array specified by the first\nargument will be overflowed if it isn’t large enough to hold the string\nspecified by the second argument._\n\n```cpp\nchar name[] = \"Some other string\";  // size of the holding array is sufficient\nstrcpy(name, \"Albert Einstein\");\n```\n\n#### `strstr`\n\n```cpp\nchar arr[] = \"Four score and seven years ago\";\nchar *ptr = strstr(arr, \"seven\");   // search for \"seven\" and return address\ncout \u003c\u003c ptr \u003c\u003c endl;                // outputs \"seven years ago\"\n```\n\n#### `strcmp`\n\n```cpp\nint strcmp(char *string1, char *string2); // function prototype\n```\n\nThe result is\n\n-   **zero** if the two strings are **equal**.\n-   **negative** if `string1` comes **before** `string2` in alphabetical order.\n-   **positive** if `string1` comes **after** `string2` in alphabetical order.\n\n#### Numeric conversion functions\n\n```cpp\n// required for using the following functions\n#include \u003ccstdlib\u003e\n\n//Converts a c-string to an integer.\nint intVal = atoi(\"1000\");\n\n//Converts a c-string to a long value.\nlong longVal = atol(\"1000000\");\n\n//Converts a c-string to a double/float value.\nfloat floatVal = atof(\"12.67\");\ndouble doubleVal = atof(\"12.67\");\n\n// returns a numeric argument converted to a c-string object\nto_string(int value);\nto_string(long value);\nto_string(long long value);\nto_string(unsigned value);\nto_string(unsigned long value);\nto_string(unsigned long long value);\nto_string(float value);\nto_string(double value);\nto_string(long double value);\n```\n\n### 3.3. Strings\n\n#### Defining `string` objects\n\n```cpp\n#include \u003cstring\u003e\nusing namespace std;\n\n// defines an empty string\nstring str0;\n\n// defines a string initialized with \"Hello\"\nstring str1 = \"Hello\";\n\n// defines a string initialized with \"Greetings!\"\nstring str2(\"Greetings!\");\n\n// defines a string which is a copy of str2. (str2 may be a string or a c-string)\nstring str3(str2);\n\n// this has to be a c-string, not a string\nchar cStr[] = \"abcdefgh\";\n\n// defines a string which is initialized to the first 5 characters in cStr\nstring str4(cStr, 5);\n\n// defines a string initialized with 10 'x' chars\nstring str5('x', 10);\n\n// defines a string which is initialized with a substring of str5.\nstring str6(str5, 2, 8);\n```\n\n#### `string` operators\n\nThere is no need to use a function such as `strcmp` to compare string objects.\nYou may use the `\u003c` , `\u003e` , `\u003c=` , `\u003e=` , `==` , and `!=` relational operators.\n\n```cpp\nstring s1 = \"Hello \";\nstring s2 = \"World!\";\nstring mystring = s1 + s2;  // concatenates s1 and s2\nchar c = mystring[0];       // returns the char at position 0 in mystring\n```\n\n#### `string` member functions\n\n![string functions 1](images/string_functions_1.png)\n![string functions 2](images/string_functions_2.png)\n![string functions 3](images/string_functions_3.png)\n\n### 4. Data Structures\n\n### 4.1. Vectors\n\n```cpp\n#include \u003cvector\u003e\nusing namespace std;\n\nvector\u003cint\u003e numbers1;                   // an empty vector of ints\nvector\u003cint\u003e numbers2(10);               // a vector of 10 ints\nvector\u003cint\u003e numbers3(10, 2);            // a vector of 10 ints, each initialized to 2\nvector\u003cint\u003e numbers4 {10, 20, 30, 40};  // a vector initialized with an initialization list\nvector\u003cint\u003e myVec(numbers4);            // a vector initialized with the elements of numbers4\n\nint val = myVec.at(index);  // return the value of the element located at index of myVec\nint* arr = myVec.data();    // return the underlying int array of myVec\nmyVec.push_back(50);        // create a last element (if myVec is full) and stores 50 in it\nmyVec.pop_back();           // remove the last element from myVec\nmyVec.size();               // get the number of elements in myVec\nmyvec.capacity();           // get the capacity of myVec\nmyVec.clear();              // completely clear the contents of myVec\nmyVec.empty();              // return true if myVec is empty\nmyVec.reverse();            // reverse the order of elements in myVec\nmyVec.resize(size, val);    // resize myVec. the new elements are initialized with val\nmyVec.swap(someVec);        // swap the contents of myVec with the contents of anotherVec\n```\n\n### 4.2. Maps\n\nMaps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.\n\nIn a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ.\n\nThe mapped values in a map can be accessed directly by their corresponding key using the bracket operator `[]`.\n\n![Maps](images/maps.png)\n\n## 5. Structs and Classes\n\nBoth `class` and `struct` declare a class. The only difference between the two is that structs have `public` members by default and classes have `private` members by default. Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.\n\nBeyond syntax, the only reason to choose one over the other is convention/style/preference. Structs are usually used as plain old data structures without any class-like features, and classes are used as aggregate data structures with private data and member functions.\n\n**Note:** _By default, structs/classes are passed to functions by value._\u003cbr\u003e\n**Note:** _You can return local structs/classes defined in functions unlike arrays._\n\n### 5.1. Structs\n\n```cpp\n// declare a struct\nstruct CityInfo\n{\n    string cityName;\n    string state;\n    long population;\n    int distance;\n};\n\n// define a struct\nCityInfo location;\nCityInfo cities[20];\n\n// initialize a struct\nCityInfo location = {\"Asheville\", \"NC\", 50000, 28};\nCityInfo location = {\"Atlanta\"};  // only cityName is initialized\nCityInfo cities[2] = {{\"Asheville\", \"NC\", 50000, 28},\n                      {\"Atlanta\", \"GA\", 45000, 90}};\n\n// access struct members\nlocation.population = 4750;\ncout \u003c\u003c location.population \u003c\u003c endl;\n\n// declare a nested struct\nstruct EmployeeInfo\n{\n    string name;\n    int employeeNumber;\n    CityInfo birthPlace;\n};\n\n// access nested struct members\nEmployeeInfo manager;\nmanager.birthPlace.population = 4750;\ncout \u003c\u003c manager.birthPlace.population \u003c\u003c endl;\n```\n\n#### Dynamically allocating structs\n\n```cpp\nstruct Circle\n{\n    double radius;\n    double diameter;\n    double area;\n};\n\nCircle* cirPtr = new Circle;\nCircle* circles = new Circle[5];\n\n// access members after dereferencing the struct pointer\ncirPtr-\u003eradius = 1.1;\ncirPtr-\u003earea = 2.2;\n\n// array elements are structs, not pointers\nfor (int i = 0; i \u003c 5; i++)\n{\n    circles[i].radius = 1.1 * i;\n    circles[i].area = 2.2 * i;\n}\n```\n\n### 5.2. Classes\n\nClasses are usually made up of a specification file and an implementation file with extensions `.h` and `.cpp`; however it is also possible to put everyting inside a single `.h` file.\n\nAs a simple example, see the [specification](code/Rectangle.h) and [implementation](code/Rectangle.cpp) files of the Rectangle class.\n\n#### Copy constructors and destructors\n\nSee the [ContactInfo](code/ContactInfo.h) class.\n\n#### Objects\n\nHere's some example usage of the [Rectangle](code/Rectangle.h) and [ContactInfo](ContactInfo.h) classes:\n\n```cpp\n// define an object from the Rectangle class (lives on stack)\nRectangle box1(12.8, 9.4);\n\n// initialize the new object with width \u0026 length of box1 (lives on stack)\n// c++ automatically creates a default copy constructor if it's not defined by programmer\nRectangle box2 = box1;  // numObjects not incremented because it's not handled in default copy constructor\nbox2.setWidth(4.7);     // assign a new width to box2\n\n// call static member function\ncout \u003c\u003c \"Number of objects: \" \u003c\u003c Rectangle::getNumObjects();    // Number of objects: 1\n\n// define a pointer to a ContactInfo class object\n// this object lives on the heap and should be deleted manually\nContactInfo* contactPtr = new ContactInfo(\"Kristen Lee\", \"555-2021\");\ncontactPtr-\u003egetName();\n\n// create a new contact and copy name \u0026 phone number from the previous one (lives on stack)\nContactInfo newContact = *contactPtr;       // our copy constructor is called here automatically\nconst char* newName = newContact.getName(); // same as \"Kristen Lee\"\n\n// the destructor is called here automatically\ndelete contactPtr;\ncontactPtr = nullptr;   // good practice for preventing errors\n\n// no need to delete other objects because they live on stack and will get deleted when the calling function returns\n```\n\n### 5.3. Inheritance\n\nThe parent class’s constructor is called before the child class’s constructor.\u003cbr\u003e\nThe destructors are called in reverse order, with the child class’s destructor being called first.\n\nSee the [Cube](code/Cube.h) class which inherits from the [Rectangle](code/Rectangle.h) class.\n\n**Base class access specification**\u003cbr\u003e\n![BCAS](images/base-class-access-specification.png)\u003cbr\u003e\n**NOTE:** If the base class access specification is left out of a declaration, the default access specification is `private.`\n\n#### Polymorphism\n\nAny class that has a virtual member function should also have a virtual destructor.\u003cbr\u003e\nEven if the class doesn’t normally require a destructor, it should still have an empty virtual destructor.\n\nSee the [GradedActivity](code/GradedActivity.h) and [PassFailActivity](code/PassFailActivity.h) and then the example usage below:\n\n```cpp\nPassFailActivity pfActivity(70);\npfActivity.setScore(72);\ndisplayGrade(pfActivity);\n\n// polymorphism requires pass by reference or by pointer\nvoid displayGrade(const GradedActivity \u0026activity)\n{\n    cout \u003c\u003c \"The activity's letter grade is \" \u003c\u003c activity.getLetterGrade() \u003c\u003c endl;\n}\n```\n\n#### Abstract Classes\n\nA **pure virtual function** is a virtual member function of a base class that **must be overridden**. When a class contains a pure virtual function as a member, that class becomes an **abstract class**.\n\n```cpp\n// this is a pure virtual function\nvirtual void foo() = 0;\n```\n\n### 5.4 Enumerated Data Types\n\n```cpp\n// each enumerator is assigned an integer starting from 0\nenum Day\n{\n    MONDAY,     // 0\n    TUESDAY,    // 1\n    WEDNESDAY,  // 2\n    THURSDAY,   // 3\n    FRIDAY      // 4\n};\n\n// assign an enumerator to an integer\nint x = THURSDAY;\n\n// can not directly assign an int to an enum variable\nDay day1 = static_cast\u003cDay\u003e(3);         // day1 = 3 is illegal!!\nDay day2 = static_cast\u003cDay\u003e(day1 + 1);  // day2 = day1 + 1 is illegal!!\n\n// compare enum values\nbool b = FRIDAY \u003e MONDAY;  // true because FIRDAY comes after MONDAY\n\n// anonymous enum types can be used when you don't need to define variables\nenum {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};\n\n// can specify integer values for all or some enumerators\nenum Color {RED, ORANGE, YELLOW = 9, GREEN, BLUE};\n```\n\n#### Strongly typed enumerators `(enum class)`\n\n```cpp\n// can specify multiple enumerators with the same name, within the same scope\nenum class President {MCKINLEY, ROOSEVELT, TAFT};\nenum class VicePresident {ROOSEVELT, FAIRBANKS, SHERMAN};\n\n// can not directly assign a strongly typed enum to an integer\n// int x = President::MCKINLEY is illegal!!\nint x = static_cast\u003cint\u003e(President::MCKINLEY);\n\n// can specify any integer data type as the underlying type\nenum class Day : char {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};\n```\n\n## 6. Templates\n\n### 6.1. Function Templates\n\n```cpp\ntemplate \u003cclass T\u003e\nvoid swap(T \u0026i, T \u0026j)\n{\n    T temp = i;\n    i = j;\n    j = temp;\n}\n\nswap(a, b);\n```\n\n### 6.2. Class Templates\n\nSee the example [SimpleVector](code/SimpleVector.h) class.\n\n## 7. File Operations\n\n| Data Type  | Description                                                    |\n| :--------: | :------------------------------------------------------------- |\n| `ifstream` | Input file stream. Can be used to read data from files.        |\n| `ofstream` | Output file stream. Can be used to create write data to files. |\n| `fstream`  | File stream. Can be used to read and write data to/from files. |\n\n#### `ifstream` and `ofstream`\n\n```cpp\n#include \u003cfstream\u003e\n\n// open an ifstream\nifstream inputFile;\ninputFile.open(\"InputFile.txt\");\n// Alternatively:\n// ifstream inputFile(\"InputFile.txt\");\n\n// open an ofstream\nofstream outputFile;\noutputFile.open(\"OutputFile.txt\");\n// Alternatively:\n// ofstream outputFile(\"OutputFile.txt\");\n\n// open ofstream in append mode\noutputFile.open(\"OutputFile.txt\", ios::out | ios::app);\n\ninputFile \u003e\u003e value;\noutputFile \u003c\u003c \"I love C++ programming\" \u003c\u003c endl;\n\ninputFile.close();\noutputFile.close();\n```\n\n#### `fstream`\n\n```cpp\n#include \u003cfstream\u003e\n\nfstream file;\n\n// open fstream in output mode\nfile.open(\"DataFile.txt\", ios::out);\n\n// open fstream in both input and output modes\nfile.open(\"DataFile.txt\", ios::in | ios::out);\n\n// read and write data in binary mode\nchar data[4] = {'A', 'B', 'C', 'D'};\nfstream file(\"DataFile.dat\", ios::binary | ios::out);\nfile.write(data, sizeof(data));\nfile.open(\"DataFile.dat\", ios::binary | ios::in);\nfile.read(data, sizeof(data));\n\n// read and write non-char data\nint numbers[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\nfstream file(\"numbers.dat\", ios::out | ios::binary);\nfile.write(reinterpret_cast\u003cchar *\u003e(numbers), sizeof(numbers));\nfile.open(\"numbers.dat\", ios::in | ios::binary);\nfile.read(reinterpret_cast\u003cchar *\u003e(numbers), sizeof(numbers));\n\n// close the file\nfile.close();\n```\n\n#### File access flags\n\nBy using different combinations of access flags, you can open files in many possible modes:\n![File Access Flags](images/file-access-flags.png)\n\n## 8. Exceptions\n\n### Standard Exceptions\n\n![Standard Exceptions](images/exceptions.jpg)\n\n| Exception               | Description                                                                                |\n| :---------------------- | :----------------------------------------------------------------------------------------- |\n| `std::exception`        | An exception and parent class of all the standard C++ exceptions.                          |\n| `std::bad_alloc`        | This can be thrown by new.                                                                 |\n| `std::bad_cast`         | This can be thrown by dynamic_cast.                                                        |\n| `std::bad_exception`    | This is useful device to handle unexpected exceptions in a C++ program.                    |\n| `std::bad_typeid`       | This can be thrown by typeid.                                                              |\n| `std::logic_error`      | An exception that theoretically can be detected by reading the code.                       |\n| `std::domain_error`     | This is an exception thrown when a mathematically invalid domain is used.                  |\n| `std::invalid_argument` | This is thrown due to invalid arguments.                                                   |\n| `std::length_error`     | This is thrown when a too big std::string is created.                                      |\n| `std::out_of_range`     | This can be thrown by the 'at' method, e.g. a std::vector and std::bitset\u003c\u003e::operator[](). |\n| `std::runtime_error`    | An exception that theoretically cannot be detected by reading the code.                    |\n| `std::overflow_error`   | This is thrown if a mathematical overflow occurs.                                          |\n| `std::range_error`      | This is occurred when you try to store a value which is out of range.                      |\n| `std::underflow_error`  | This is thrown if a mathematical underflow occurs.                                         |\n\n### Throwing an Exception\n\n```cpp\ndouble divide(int numerator, int denominator)\n{\n    if (denominator == 0)\n    {\n        // throws an exception of type \"string\"\n        throw string(\"ERROR: Cannot divide by zero.\\n\");\n    }\n    else\n    {\n        return static_cast\u003cdouble\u003e(numerator) / denominator;\n    }\n}\n```\n\n### Handling an Exception\n\n```cpp\ntry\n{\n    double quotient = divide(num1, num2);\n    cout \u003c\u003c \"The quotient is \" \u003c\u003c quotient \u003c\u003c endl;\n}\ncatch (string exceptionString)  // only catches exceptions of type \"string\"\n{\n    cout \u003c\u003c exceptionString;\n}\n```\n\nThere are two possible ways for a thrown exception to go uncaught:\n\n1. The try/catch construct contains no catch blocks with an exception parameter of the right data type.\n2. The exception is thrown from outside a try block.\n\n_In either case, the exception will cause the entire program to abort execution._\n\nIf an exception is thrown by the member function of a class object, then the class destructor is called. If any other objects had been created in the try block,their destructors will be called as well.\n\n### Multiple Exceptions\n\n```cpp\n// define a custom exception class\nclass MyException: public std::exception\n{\n    public:\n        MyException(const char* message) : msg(message) {}\n        MyException(const std::string\u0026 message): msg(message) {}\n\n        const char* what() const throw()\n        {\n            return msg.c_str();\n        }\n\n    protected:\n        std::string msg;\n};\n\ndouble divide(int numerator, int denominator)\n{\n    if (denominator == 0)\n    {\n        // throws an exception of type \"string\"\n        throw string(\"ERROR: Cannot divide by zero.\\n\");\n    }\n    else if (numerator \u003c 0 || denominator \u003c 0)\n    {\n        // throw an exception of type \"MyException\"\n        throw MyException(\"Negative arguments not allowed!\");\n    }\n    else\n    {\n        return static_cast\u003cdouble\u003e(numerator) / denominator;\n    }\n}\n\n// use the function\ntry\n{\n    double quotient = divide(num1, num2);\n    cout \u003c\u003c \"The quotient is \" \u003c\u003c quotient \u003c\u003c endl;\n}\ncatch (string msg)  // only catches exceptions of type \"string\"\n{\n    cout \u003c\u003c msg;\n}\ncatch (MyException\u0026 e)\n{\n    cout \u003c\u003c \"Error: \" \u003c\u003c e.what() \u003c\u003c endl;\n}\n```\n\n### Rethrowing an Exception\n\n```cpp\ntry\n{\n    // assume that this function throws an exception of type \"exception\"\n    doSomething();\n}\ncatch(exception)\n{\n    throw;  // rethrow the exception\n}\n```\n\n## 9. Operator Overloading\n\nYou can customize operators to work with your custom classes. Take a look at the [MyInt](code/MyInt.h) class to see an example. Some common operators that can be overloaded are the following:\n\n![Common Operators](images/common-operators.png)\n\n## 10. `auto` Keyword\n\nStarting from C++11, the `auto` keyword can be used to _infer_ the type of a variable.\n\n```cpp\nauto x = 5; // C++ will infer this is an integer\nstd::string myName = \"Billy\";\nauto nameCopy = myName; // C++ will infer 'nameCopy' based on the 'myName' variable\n```\n\nNote that this only works when initializing a variable upon creation. Variables created without initialization values can not use this feature.\n\nIn C++14, the `auto` keyword was extended to be able to auto-deduce a function’s return type:\n\n```cpp\nauto add(int x, int y)\n{\n    return x + y;\n}\n```\n\nSince `x + y` evaluates to an integer, the compiler will deduce this function should have a return type of `int`.\n\nA good rule of thumb is that `auto` is okay to use when defining a variable, because the object the variable is inferring a type from is right there, on the right side of the statement. However, with functions, that is not the case -- there’s no context to help indicate what type the function returns. A user would actually have to dig into the function body itself to determine what type the function returned. It’s much less intuitive, and therefore more error prone.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futkuufuk%2Fcpp-quick-reference","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Futkuufuk%2Fcpp-quick-reference","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futkuufuk%2Fcpp-quick-reference/lists"}