{"id":19233548,"url":"https://github.com/hoangtien2k3/code-c-plus-plus","last_synced_at":"2025-04-21T04:33:19.751Z","repository":{"id":65697190,"uuid":"589509590","full_name":"hoangtien2k3/Code-C-plus-plus","owner":"hoangtien2k3","description":"Master your language C++. design patterns example - Java - C++. Multiple projects. Software engineering experiences. ","archived":false,"fork":false,"pushed_at":"2023-04-24T15:36:15.000Z","size":22363,"stargazers_count":4,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-01T09:46:56.014Z","etag":null,"topics":["c","cpp"],"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/hoangtien2k3.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}},"created_at":"2023-01-16T09:39:48.000Z","updated_at":"2023-03-16T18:24:19.000Z","dependencies_parsed_at":"2024-03-16T11:39:45.765Z","dependency_job_id":null,"html_url":"https://github.com/hoangtien2k3/Code-C-plus-plus","commit_stats":null,"previous_names":["hoangtien2k3/code-c-plus-plus"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtien2k3%2FCode-C-plus-plus","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtien2k3%2FCode-C-plus-plus/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtien2k3%2FCode-C-plus-plus/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtien2k3%2FCode-C-plus-plus/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hoangtien2k3","download_url":"https://codeload.github.com/hoangtien2k3/Code-C-plus-plus/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249996234,"owners_count":21358094,"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","cpp"],"created_at":"2024-11-09T16:11:04.450Z","updated_at":"2025-04-21T04:33:18.289Z","avatar_url":"https://github.com/hoangtien2k3.png","language":"C++","readme":"# Code-C-plus-plus\n Master your language C++. Create portfolio projects that showcase your new skills to help land your dream job.\n##\n* Link_PDF:  [300 bài code thiếu nhi.pdf](https://github.com/hoangtien2k3/Code-C-plus-plus/files/8533256/300.bai.code.thi.u.nhi.pdf)\n* Link Web hay: https://www.javatpoint.com/ \n* Link Web hay: https://viettuts.vn/\n\n\u003cb\u003eOOP\u003c/b\u003e is an approach to program organizational and development that attempts to eliminate some of the pitfalls of proceedural programming.\u003cbr /\u003e\n\n# Object Oriented Programming\n\n## Why OOP\n\nObject Oriented Programming has a capability of programming/coding (more precisely, MODELLING) any(most of) real world scenarios.\n\u003cb\u003eNote* \u003c/b\u003e C++ is not purely object oriented, JAVA is a purely object oriented programming language\n\n\n### Classes\n\n### Objects\n\n### Class Diagrams\n\n### Syntax\n\n```cpp\n#include\u003ciostream\u003e\nusing namespace std;\n\nclass abc\n{\n    int a,b;\n  public:\n    void add(int a, int b) // Inline Function -- Member function defined inside the class\n    {\n        cout\u003c\u003ca+b;\n    }\n    void subtract(int a, int b);\n};\n\nvoid abc::subtract(int a, int b) // Member function defined outside the class\n{\n    cout\u003c\u003ca-b;\n}\n\nint main() {\n    abc x;\n    x.add(5,10);\n    x.subtract(20,10);\n    return 0;\n}\n\n```\n\n#### Why using namespace std?\n`cout` is one of the standard classes, which should be accessed be `std::cout`, to ease the process of writing code we write `using namespace std;`\n\n## 5 Characteristics of OOP\n\n  * Data Encapsulation\n  * Data Abstraction\n  * Polymorphism\n  * Inheritence\n  * Modularity\n\n## Polymorphism\n\nPolymorphism (Looking alike but exhibit different characteristics).In C++, polymorphism can be either\nstatic polymorphism or\ndynamic polymorphism\n\u003cbr /\u003e\nC++ implements static polymorphism through\noverloaded functions\noverloaded operators\n\u003cbr /\u003e\u003cbr /\u003e\nThree ways of achieving overloading in C++\n  * Function Overloading\n  * Operator Overloading\n  * Dynamic Binding\n\n## Overloading\n\nA name having two or more distinct meanings\u003cbr /\u003e\n**Function Overloading** -- A function having two or more distinct meaning\n**Operator Overloading** -- When two or more distinct meanings are defined for a single operator\n\u003cbr /\u003e For example -- '-' can be unary as well as binary, '*' is used for multiplication as well as pointers\n\n[See Example](funOver.cpp)\n\n#### Signature\n\nCombination of function's name and its parameter types (in order).\nOr, a function's arguement list is known as the function's signature. Overloaded functions are distinguished by their signatures\n\nSignature is only on the parameter's, **NOT** on the return type\n\n## Function Overloading -- Finding the best match\n\nA call to an overloaded function is resolved to a particular instance of the function, there are three possible cases, a function call may result in:\u003cbr /\u003e\n  * **One Match** - A match is found for the function call\n  * **No Match** - No match is found for the function call\n  * **Ambiguous Match** - More than one defined instance for the function call.\n\n## Match Techniques\n\n### Exact Match\n\nFor example, there are two functions with same name afunc:\n\u003cbr/\u003e\tvoid afunc(int);\n\u003cbr/\u003e void afunc(double);\nThe function call afunc(0);\nis matched to void afunc(int); and compiler invokes corresponding function definition\nas 0 (zero) is of type int\n\n### Match through promotion\n\nIf no exact match is found, an attempt is made to achieve a match through promotion of the actual argument.\nRecall that the conversion of integer types (char, short, enumerator, int) into int - integral promotion\n\u003cbr /\u003e\nFor example, consider the following code fragment:\u003cbr/\u003e\n\tvoid afunc (int);\u003cbr/\u003e\n\tvoid afunc (float);\u003cbr/\u003e\n\tafunc (‘c’);\nWill invoke afunc(int)\n\n## Constructors and Destructors\n\n## Constructors\n\nA constructor is a special member function whose task is to initialize the objects of its class. It's name is same as the name of the class.\nThe constructor is invoked whenever an object of it's associated class  is created.\u003cbr /\u003e\nIt is called constructor because it constructs the values of data members of the class.\n\n\u003cbr /\u003e**Example**\n```cpp\nclass add {\n    int m,n;\n  public:\n    add (void);\n};\n\nadd::add(void) {\n    m=0;\n    n=0;\n}\n```\n\n### Parameterized Constructors\n\nWhen a constructor is parametrized, we must pass the initial values as arguements to the constructor function.\n\n### Copy Constructor\n\nA copy constructor is used\n```cpp\nsample::sample (sample \u0026i) {\n    a=i.a;\n    b=i.b;\n}\n```\n\n#### Multiple constructors in a class\n\n* constructor overtloading is possible in c++.\n* Default arguement constructors are allowed `A::A(int x=0)`\n\n[See an example here](copy.cpp)\n\n## Destructor\n\nA destructor is used to destroy the objects that have been created by a constructor\nDestructor never takes any arguements nor returns any value\nIt will be invoked implicitly by the compiler upon exit from the program (or any block/function).\n\n## Function calling methods\n\n1. Call by Value\n2. Call by Address\n3. Call ny Reerance\n\n## Dynamic memory Allocation in C++\n\nC++ has two new operators apart form malloc() and calloc(), called `new` and `delete`\n\n### New and delete in C++\n\nSimilar to malloc and free in C\nBut there is an option to initialize memory\nCan be used allocate memory for single or array of elements\nIf memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated.\nIf sufficient memory is not available, the new operator returns NULL.\nDynamically allocated object/array exists until the delete operator destroys it\n\n[1. Dynamic Memory Allocation](dynAlloc.cpp)\n[2. Dynamic Memory Allocation for Arrays](dynamicArray.cpp)\n[3. Dynamic Memory Allocation for Objects](dynamicObject.cpp)\n\n## Exception handling\n\nPreventing program/Software to crash in case of wrong inputs by throwing appropriate error messages/.\n\n**try, catch and throw**\n\n### TRY\n\n```cpp\ntry {\n    .\n    .\n    // Possibly an unexpected situation\n    throw(val1);\n    .\n    .\n    .\n    // Possibly an unexpected situation\n    throw(val2);\n    .\n    .\n    .\n}\n\ncatch (val1) {\n    .. ..\n    .. ..\n    .. ..\n}\ncatch (val2) {\n    .. ..\n    .. ..\n    .. ..\n}\n\n\ncatch (...) {    // catch(...) catches any throw\n\n}\n```\n\n## Friend Function\n\nA friend function is a function that can access the non-public members of a class, even though the function itself is not a member of the class.\n\n### Doesn't it violate the concept of data hiding\n\nThe concepts of encapsulation and data hiding dictate that non-member functions should not be able to access an object’s private or protected data.\nHowever, there are situations where such rigid discrimination leads to considerable inconvenience.\nA friend function is a normal function with special access privileges.\n\n### More about friend function\n\nA friend function of a class is a non-member function of a class that has the right to access all private and protected (non-public) members of the class.\nFriend function prototype should be placed inside the class definition (can be any where inside the class definition).\nFriend function definition should be outside the class scope.\nEven though the prototypes of friend functions appear in the class definition, friends are not member functions.\n\nA friend function of a class can be a\n\n  * function (non-member of a class)\n  * member function of another class\n  * function template\n\nTo declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend.\nFriend functions are used in Operator overloading to increase the versatility of operators.\n\n### Syntax\n\n```cpp\nclass ClassName  {\n    // Some statements\n    friend  returnType  functionName( arguments ); // friend function declaration\n    // Some Statements\n};\n// friend function definition does not start with friend keyword\nreturnType  functionName( arguments )  {\n    ... ... ...\n// private and protected data of the above class can be accessed from this function\n    ... ... ...\n}\nint main( ) {\n    functionName( arguments ); // Call to the friend function\n}\n```\n\n[**See a sample program**](friend.cpp)\n\n### Difference between Friend function and Member function\n\n|Member Function|Friend Functoon|\n|--|---|\n|It is invoked through an object|Not invoked through an object since it is a non-member of a class \u003cbr /\u003e If the friend function of class X is a member function of class  Y, then it must be invoked through an object of class Y |\n|Can access the non-public members of the class directly|Can access the non-public members of the class only through an object (since this pointer is not visible)|\n\n## Friend Class\n\nMember functions of a class X operate on the data members of Class X.\nAt times, we need a helper class to operate on non-public data members of the class X. In such circumstances, the helper class has to be treated as a friend of class X to access the non-public data members of class X.\nSo, a class can be a friend of another class\n\nFor example:\u003cbr /\u003e\nIf class Y is a friend of class X then \u003cbr /\u003e\nAll the member functions of class Y can access the non-public members of class X\n\n### Friendship is not symmetric\n\nIf class Y is a friend of class X then\nclass X is not a friend of class Y\n\n### Friendship is not transitive\n\nIf class X is a friend of class Y and If class Y is a friend of class Z then\nclass X is not a friend of class Z\n\n### Syntax\n\n```cpp\n\nclass employer;// forward declaration of class Y\nclass employee {\n    ... ...\n\tfriend class employer;// friend class declaration\n\t... ...\n};\nclass employer {\n// All the member functions of class employer can access non-public members of class employee using an object\n};\n\n\n```\n\n## Operator overloading\n\nC++ allows most of the operators within the language to be overloaded so that they work with classes.  This\n- allows the language to be extended to cover new situations\n- enhances program readability\n- enhances program functionality\n- is an essential components of C++ templates and the standard templates library\n\n### Restrictions\n\nThe operators .  ::  ?:   sizeof  **may not** be overloaded.\n\nAll other operators can be overloaded\n\nAn operator is overloaded by writing a non-static member function definition or non-member\nfunction definition as you normally would, except that the function name\nstarts with the keyword operator followed by the symbol for the operator being overloaded.\n\n**For example**, the function name operator+ would be used to overload the addition operator (+)\nfor use with objects of a particular class.\n\n[**Overloading binary addition operator**](opOver.cpp) \u003cbr /\u003e\n[**Overloading unary subtraction operator**](opOverUnary.cpp) \u003cbr /\u003e\n[**Overloading unary increment operator**](incrementOver.cpp) \u003cbr /\u003e\n[**Overloading subscript operator**](incrementOver.cpp) \u003cbr /\u003e\n\n## Inheritance\n\nInheritance means deriving qualities and characteristics from parents or ancestors. \n\nInheritance in Object Oriented Programming can be described as a process of creating new classes from existing classes which will have the properties similar to that of parent classes.\nOr simply, Inheritance is the process by which objects of one class acquire the properties of objects of another class in the hierarchy.\n\nSubclasses provide specialized behavior from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times.\n\nReusing existing code saves time and money and increases a program’s reliability.\n\n![image](https://user-images.githubusercontent.com/26179770/36838639-b9c269e4-1d65-11e8-9c98-506477719a4d.png)\n\nNew classes can be built from the existing classes. It means that we can add additional features to an existing class without modifying it. The new class is referred as derived class or subclass and the original class is known as base classes or super class.\n\n### Syntax\n\n```cpp\nclass derivedClasas: accessSpecifier baseClass\n```\n\n## Access Specifiers\n\nAccess specifiers are (as the name suggests) specifiers which tell what should be the privacy of the content, and how much content wee can access.\n\nAccess specifier can be public, protected and private. The default access specifier for data members is private. Access specifiers affect accessibility of data members of base class from the derived class. In addition, it determines the accessibility of data members of base class outside the derived class.\n\n## Inheritance Access Specifiers\n\n### Public\n\nThis inheritance mode is used mostly. In this the protected member of Base class becomes protected members of Derived class and public becomes public.\n\n### Protected\n\nIn protected mode, the public and protected members of Base class becomes protected members of Derived class.\n\n### Private\n\nIn private mode the public and protected members of Base class become private members of Derived class.\n\n## Types Of Inheritance\n\n- [Single Inheritance](#single-inheritance)\n- [Multiple Inheritance](#single-inheritance)\n- [Multi Level Inheritance](#single-inheritance)\n- [Hierarchical Inheritance](#single-inheritance)\n- [Hybrid Inheritance](#single-inheritance)\n\n### Single inheritance\n\nOne child class inherits one parent class\n\n![image](https://user-images.githubusercontent.com/26179770/36835325-d9d905d0-1d5b-11e8-99f6-f53e93ed5a38.png)\n\n\n[**See a sample program here**](./inheriance/single.cpp)\n\n### Multiple Inheritance\n\nWhen one child cass inherits properties of  more than one parent classes.\nSimply, one subclass and many super classes form a multiple inheritance.\n\n![image](https://user-images.githubusercontent.com/26179770/36891750-9fad27ec-1e28-11e8-9dd5-87b935688bd7.png)\n\n[**See a sample program here**](./inheritance/multiple.cpp)\n\n### Multilevel Inheritance\n\nAs the name suggests, in this type of inheritance, there are multiple levels of inheritance.  This is analogous to grand parents, then parents then children.\n\n![image](https://user-images.githubusercontent.com/26179770/37459322-b018b41c-286d-11e8-9382-dc31f5690ccd.png)\n\nExample:\n![image](https://user-images.githubusercontent.com/26179770/37459129-2b6145f4-286d-11e8-83ee-bfcafe56f689.png)\n\n[**See a sample program here**](./inheritance/multilevel.cpp)\n\n### Hierarchical Inheritance\n\nIn this case the inheritance pattern forms a hierarchy, i.e., there are multiple derived classes of same base class.\n\n![image](https://user-images.githubusercontent.com/26179770/37459413-f5d3db94-286d-11e8-9e82-c2675b36c8ac.png)\n\n[**See a sample program here**](./inheritance/hierarchical.cpp)\n\n### Hybrid Inheritance\n\nHybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.\n\n![image](https://user-images.githubusercontent.com/26179770/37460441-3e203598-2871-11e8-9b7b-e3f1150aaf07.png)\n\n[**See a sample program here**](./inheritance/hybrid.cpp)\n\n## Diamond Problem\n\nThis is the problem arised in some cases of hybrid inheritance. In this problem a Derived class will have multiple paths to a Base class. This will result in duplicate inherited members of the Base class.\n\n![image](https://user-images.githubusercontent.com/26179770/37461230-a6283a62-2873-11e8-8194-c30136e21f1d.png)\n\n## Virtual Base Class\n\nVirtual base class is used in situation where a derived have multiple copies of base class to avoid dreaded diamonds problem. \u003cbr\u003e\nreference: http://www.tutorialdost.com/Cpp-Programming-Tutorial/51-Cpp-Virtual-Base-Class.aspx\n\n![image](https://user-images.githubusercontent.com/26179770/37461316-f3efedb2-2873-11e8-8a33-576936ccc2d2.png)\n\n\n### Example without using virtual class\n\n```cpp\n#include\u003ciostream.h\u003e\n#include\u003cconio.h\u003e\n\nclass ClassA\n{\n    public:\n    int a;\n};\n\nclass ClassB : public ClassA\n{\n    public:\n    int b;\n};\nclass ClassC : public ClassA\n{\n    public:\n    int c;\n};\n\nclass ClassD : public ClassB, public ClassC\n{\n    public:\n    int d;\n};\n\nvoid main()\n{\n\n    ClassD obj;\n\n    obj.a = 10;        //Statement 1, Error occur\n    obj.a = 100;       //Statement 2, Error occur\n\n    obj.b = 20;\n    obj.c = 30;\n    obj.d = 40;\n\n    cout\u003c\u003c \"\\n A : \"\u003c\u003c obj.a;\n    cout\u003c\u003c \"\\n B : \"\u003c\u003c obj.b;\n    cout\u003c\u003c \"\\n C : \"\u003c\u003c obj.c;\n    cout\u003c\u003c \"\\n D : \"\u003c\u003c obj.d;\n\n}\n```\n\n**This will result in error**\nTherefore, to avoid such situations, we use virtual class\n\n### Example  with virtual base class\n\n```cpp\n#include\u003ciostream.h\u003e\n#include\u003cconio.h\u003e\n\nclass ClassA\n{\n    public:\n    int a;\n};\n\nclass ClassB : virtual public ClassA\n{\n    public:\n    int b;\n};\nclass ClassC : virtual public ClassA\n{\n    public:\n    int c;\n};\n\nclass ClassD : public ClassB, public ClassC\n{\n    public:\n    int d;\n};\n\nvoid main()\n{\n\n    ClassD obj;\n\n    obj.a = 10;        //Statement 1\n    obj.a = 100;       //Statement 2\n\n    obj.b = 20;\n    obj.c = 30;\n    obj.d = 40;\n\n    cout\u003c\u003c \"\\n A : \"\u003c\u003c obj.a;\n    cout\u003c\u003c \"\\n B : \"\u003c\u003c obj.b;\n    cout\u003c\u003c \"\\n C : \"\u003c\u003c obj.c;\n    cout\u003c\u003c \"\\n D : \"\u003c\u003c obj.d;\n\n}\n\nOutput :\n\n        A : 100\n        B : 20\n        C : 30\n        D : 40\n\n```\n\nHere, ClassD have only one copy of ClassA and statement 4 will overwrite the value of a, given in statement 3.\n\n## Virtual Functions\n\nThere are many cases where there is a function declared in base class and then again declared in the child class, i.e., that function is overridden.\nSo basically, a virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class.\n\nCharacteristics of virtual functions:\n\n* Ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.\n\n* Used to achieve dynamic/runtime polymorphism\n\n* Functions are declared with a virtual keyword in base class.\n\n* The resolving of function call is done at Run-time.\n\n### Rules for virtual functions\n\n* They Must be declared in public section of class.\n\n* Virtual functions cannot be static and also cannot be a friend function of another class.\n\n* Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.\n\n* The prototype of virtual functions should be same in base as well as derived class.\n\n* They are always defined in base class and overridden in derived class. \n\n* It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used.\n\n* A class may have virtual destructor but it cannot have a virtual constructor.\n\n[See a sample program here](./virtual.cpp)\n\n## Pure Virtual Functions (Abstract Classes)\n\nSometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class.\n\n[See a sample program here](./absract.cpp)\n\n## Templates\n\nTemplate is a kind of macro that supports the generic programming which allows to develop the reusable components.\nIt is one of the main features of object oriented language such as C++.\nActually, it allows the declaration of data items without specifying their exact data type.\n\n## 2 Types pf templates\n\n1. Function Templates\n2. Class Templates\n\n### Function Templates\n\nFunction templates are generic functions, which are operating on different data items. \u003cbr/\u003e\nThey describe a function format that when instantiated with particulars generates a function definition, basically it acts like a template schema which can be used\nfor parameters with any datatype, instead of some fixed data type\n\n* Avoids redifinition of function\n\n* Makes code more reusable (write once, use multiple times)\n\nThe C++ language allows the compiler to generate multiple versions of a function by allowing parameterized data types and hence it supports the parameterized polymorphism.\n\nThe data items (types) are not declared while defining the function.\n\nOnce when the function call is made using appropriate data type, then the template function is transformed to operate on that specific data types.\n\n#### Syntax\n\n```cpp\ntemplate\u003cclass type\u003e\nreturntype functionname(arguments)\n{\n    .......\n    statements;\n    .......\n}\n```\n\n[See sample program 1 here](./template.cpp)\n[See sample program 2 here](./tempAdd.cpp)\n\n### Class Template\n\nGeneric classes with template data variables and template member functions\n\n[See a sample program here](./classTemplate.cpp)\n\n## Standard Template Libraries\n\nThe Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite  for working with STL.\n\n## 4 components of STL\n\n* Algorithms\n\n* Containers\n\n* Functions\n\n* Iterators\n\n### \n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangtien2k3%2Fcode-c-plus-plus","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhoangtien2k3%2Fcode-c-plus-plus","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangtien2k3%2Fcode-c-plus-plus/lists"}