C++

C++ is a cross-platform language that can be used to create high-performance applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and memory.

The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20.

Java
Why Use C++
C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.

C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa.



Difference between C and C++
C++ was developed as an extension of C, and both languages have almost the same syntax.

The main difference between C and C++ is that C++ support classes and objects, while C does not.
  1. C++ Syntax
    C++ Syntax

    Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.

    Line 2: using namespace std means that we can use names for objects and variables from the standard library.
    Don't worry if you don't understand how #include <iostream> and using namespace std works. Just think of it as something that (almost) always appears in your program.

    Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.

    Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.

    Line 5: cout (pronounced "see-out") is an object used together with the insertion operator ( <<) to output/print text. In our example it will output "Hello World" .

    Note: Every C++ statement ends with a semicolon ;.


    Note: The body of int main() could also been written as: int main () { cout << "Hello World! " ; return 0; }

    Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.

    Line 6: return 0 ends the main function.

    Line 7: Do not forget to add the closing curly bracket } to actually end the main function.
                         
                            #include <iostream>
                                using namespace std;
                                
                                int main() {
                                  cout << "Hello World!";
                                  return 0;
                                }
                            
                    
  2. Print Text
    Print Text
    The cout object, together with the << operator, is used to output values/print text
                     
                    cout << "Hello World!";
                
            

    print on New Lines

                     
      cout << "Hello World!" << endl;
                
            
  3. C++ Comments
    C++ Comments
    Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

    Single-line Comments
    Single-line comments start with two forward slashes (//).

    Any text between // and the end of the line is ignored by the compiler (will not be executed).

    single linecomment

        
            // This is a comment
    
    

    Multi-Line comments

        
            /* The code below will print the words Hello World
    to the screen, and it is amazing */
    
    
  4. C++ Variables
    C++ Variables
    Variables are containers for storing data values.

    In C++, there are different types of variables, for example:
    1. String - stores text, such as "Hello". String values are surrounded by double quotes
    2. int - stores integers (whole numbers), without decimals, such as 123 or -123
    3. double - stores floating point numbers, with decimals, such as 19.99 or -19.99
    4. char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
    5. bool - stores values with two states: true or false

    Declaring (Creating) Variables (Syntax)

        
            type variableName = value;
    
    
    
        int myNum = 15;
    cout << myNum;
    
    
  5. Identifiers
    Identifiers
    All C++ variables must be identified with unique names.

    These unique names are called identifiers.

    Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).


    Note: It is recommended to use descriptive names in order to create understandable and maintainable code
    The general rules for naming variables are:


    Names can contain letters, digits and underscores

    Names must begin with a letter or an underscore (_)

    Names are case sensitive (myVar and myvar are different variables)

    Names cannot contain whitespaces or special characters like !, #, %, etc.

    Reserved words (like C++ keywords, such as int) cannot be used as names
  6. Constants
    Constants
    When you do not want others (or yourself) to change existing variable values, use the const

    keyword (this will declare the variable as "constant", which means unchangeable and read-only)
                            
                                const int myNum = 15;  // myNum will always be 15   
                        
                        
  7. C++ User Input
    C++ User Input
    You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

    cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

    In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x



    cout is pronounced "see-out". Used for output, and uses the insertion operator ( <<)

    cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
                                
                                    cin >> x; // Get user input from the keyboard
                            
                            
  8. C++ Data Types
    C++ Data Types
    Data Type Size Description
    boolean 1 byte Stores true or false values
    char 1 byte Stores a single character/letter/number, or ASCII values
    int 2 or 4 bytes Stores whole numbers, without decimals
    float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits
    double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
  9. C++ Operators
    C++ Operators
    C++ Operators
    Operators are used to perform operations on variables and values.

    Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable

    Arithmetic Operators
    Arithmetic operators are used to perform common mathematical operations.
    Operator Name Description Example
    + Addition Adds together two values x + y
    - Subtraction Subtracts one value from another x - y
    * Multiplication Multiplies two values x * y
    / Division Divides one value by another x / y
    % Modulus Returns the division remainder x % y
    ++ Increment Increases the value of a variable by 1 ++x
    -- Decrement Decreases the value of a variable by 1 --x


    Assignment Operators
    Assignment operators are used to assign values to variables.
    Operator Example Same As
    = x = 5 x = 5
    += x += 3 x = x + 3
    -= x -= 3 x = x - 3
    *= x *= 3 x = x * 3
    /= x /= 3 x = x / 3
    %= x %= 3 x = x % 3
    &= x &= 3 x = x & 3
    |= x |= 3 x = x | 3
    ^= x ^= 3 x = x ^ 3
    >>= x >>= 3 x = x >> 3
    <<= x <<= 3 x = x << 3


    Comparison Operators
    Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.
    Operator Name Example
    == Equal to x == y
    != Not equal x != y
    > Greater than x > y
    < Less than x < y
    >= Greater than or equal to x >= y
    <= Less than or equal to x <= y


    Logical Operators
    As with comparison operators, you can also test for true or false values with logical operators.
    Operator Name Description Example
    &&  Logical and Returns true if both statements are true x < 5 &&  x < 10
    ||  Logical or Returns true if one of the statements is true x < 5 || x < 4
    ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)


    In the example below, we use the + operator to add together two values
  10. C++ Strings
    C++ Strings
    Strings are used for storing text.
    A string variable contains a collection of characters surrounded by double quotes

    Include the string library

                        
    #include <string>     
                    
                    

                        
                            string greeting = "Hello";     
                    
                    
  11. C++ String Concatenation
    C++ String Concatenation
    String Concatenation
    The + operator can be used between strings to add them together to make a new string. This is called concatenation

                                            
                                                string firstName = "John ";
    string lastName = "Doe";
    string fullName = firstName + lastName;
    cout << fullName;
                                        
                                        

                                        
                                            string firstName = "John ";
    string lastName = "Doe";
    string fullName = firstName.append(lastName);
    cout << fullName;
                                    
                                    
  12. C++ String Length
    C++ String Length
    To get the length of a string, use the length() function

    You might see some C++ programs that use the size() function to get the length of a string. This is just an alias of length(). It is completely up to you if you want to use length() or size()
                        
                            string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                            cout << "The length of the txt string is: " << txt.length();
                        
                        
  13. C++ Access Strings
    C++ Access Strings
    Access Strings
    You can access the characters in a string by referring to its index number inside square brackets [].

    This example prints the first character in myString
                        
                            string myString = "Hello";
    cout << myString[0];
    // Outputs H
                        
                        
  14. escape characters in C++
    escape characters in C++
    The solution to avoid this problem, is to use the backslash escape character.
    The backslash (\) escape character turns special characters into string characters
    Escape character Result Description
    \' ' Single quote
    \" " Double quote
    \\ \ Backslash
    Escape Character Result
    \n New Line
    \t Tab
  15. C++ Math
    C++ Math
    C++ Math
    C++ has many functions that allows you to perform mathematical tasks on numbers.

    Other Math Functions
    Function Description
    abs(x) Returns the absolute value of x
    acos(x) Returns the arccosine of x
    asin(x) Returns the arcsine of x
    atan(x) Returns the arctangent of x
    cbrt(x) Returns the cube root of x
    ceil(x) Returns the value of x rounded up to its nearest integer
    cos(x) Returns the cosine of x
    cosh(x) Returns the hyperbolic cosine of x
    exp(x) Returns the value of Ex
    expm1(x) Returns ex -1
    fabs(x) Returns the absolute value of a floating x
    fdim(x, y) Returns the positive difference between x and y
    floor(x) Returns the value of x rounded down to its nearest integer
    hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
    fma(x, y, z) Returns x*y+z without losing precision
    fmax(x, y) Returns the highest value of a floating x and y
    fmin(x, y) Returns the lowest value of a floating x and y
    fmod(x, y) Returns the floating point remainder of x/y
    pow(x, y) Returns the value of x to the power of y
    sin(x) Returns the sine of x (x is in radians)
    sinh(x) Returns the hyperbolic sine of a double value
    tan(x) Returns the tangent of an angle
    tanh(x) Returns the hyperbolic tangent of a double value

                                        
                                            #include <cmath>
                                        
                                        

                                        
                                            cout << max(5, 10);
                                        
                                        
                                            
                                                cout << min(5, 10);
                                            
                                            
  16. Conditional statements
    Conditional statements
    The if Statement

    Use the if statement to specify
    a block of C++ code to be executed if a condition is true.


    The else Statement
    Use the else statement to specify a block of code to be executed if the condition is false.


    The else if Statement
    Use the else if statement to specify a new condition if the first condition is false.


    Short Hand If...Else (Ternary Operator)
    There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements


    C++ Switch Statements
    Use the switch statement to select one of many code blocks to be executed.


    The break Keyword
    When C++ reaches a break keyword, it breaks out of the switch block.
    This will stop the execution of more code and case testing inside the block.
    When a match is found, and the job is done, it's time for a break. There is no need for more testing.


    The default Keyword
    The default keyword specifies some code to run if there is no case match

                                        
                                            if (condition) {
                                                // block of code to be executed if the condition is true
                                              }
                                        
                                        

                                                
                                                    if (condition) {
                                                        // block of code to be executed if the condition is true
                                                      } else {
                                                        // block of code to be executed if the condition is false
                                                      }
                                                
                                                

                                                
                                                    if (condition1) {
                                                        // block of code to be executed if condition1 is true
                                                      } else if (condition2) {
                                                        // block of code to be executed if the condition1 is false and condition2 is true
                                                      } else {
                                                        // block of code to be executed if the condition1 is false and condition2 is false
                                                      }
                                                
                                                

                                                  
                                                    variable = (condition) ? expressionTrue : expressionFalse;
                                                  
                                                  
                                                    
                                                        string result = (time < 18) ? "Good day." : "Good evening.";
                                                    
                                                    

                                                  
                                                    switch(expression) {
                                                        case x:
                                                          // code block
                                                          break;
                                                        case y:
                                                          // code block
                                                          break;
                                                        default:
                                                          // code block
                                                      }
                                                  
                                                  
  17. C++ Loops
    C++ Loops
    C++ Loops
    Loops can execute a block of code as long as a specified condition is reached.

    Loops are handy because they save time, reduce errors, and they make code more readable.


    C++ While Loop
    The while loop loops through a block of code as long as a specified condition is true


    The Do/While Loop
    The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


    C++ For Loop
    When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop


    C++ Break
    You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.

    The break statement can also be used to jump out of a loop.


    C++ Continue
    The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

                                                
                                                    while (condition) {
                                                        // code block to be executed
                                                      }
                                                
                                                

                                                
                                                    do {
                                                        // code block to be executed
                                                      }
                                                      while (condition);
                                                
                                                

                                                
                                                    for (statement 1; statement 2; statement 3) {
                                                        // code block to be executed
                                                      }
                                                
                                                

                                                  
                                                    for (type variableName : arrayName) {
                                                        // code block to be executed
                                                      }
                                                  
                                                  

                                                  
                                                    break;
                                                  
                                                  

                                                  
                                                    continue;
                                                  
                                                  
  18. C++ Arrays
    C++ Arrays
    C++ Arrays
    Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

    To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store


    Access the Elements of an Array
    You access an array element by referring to the index number inside square brackets [].

    This statement accesses the value of the first element in cars

    Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

                                                
     string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
     cout << cars[0];
                                                
                                                

                                                                                        
                                                    cars[0] = "Opel";
       
                                                
                                                

                                                                                        
                                                    int myNumbers[5] = {10, 20, 30, 40, 50};
                                                    cout << sizeof(myNumbers);
                                                
                                                

                                                                                        
                                                    string letters[2][4] = {
                                                        { "A", "B", "C", "D" },
                                                        { "E", "F", "G", "H" }
                                                      };
                                                      
                                                      cout << letters[0][2];  // Outputs "C"                                       
                                                

                                                                                        
                                                    for (int i = 0; i < 2; i++) {
                                                        for (int j = 0; j < 4; j++) {
                                                          cout << letters[i][j] << "\n";
                                                        }
                                                      }                       
                                                
  19. C++ Structures
    C++ Structures
    C++ Structures
    Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

    Unlike an array, a structure can contain many different data types (int, string, bool, etc.).


    Create a Structure
    To create a structure, use the struct keyword and declare each of its members inside curly braces.

    After the declaration, specify the name of the structure variable (myStructure in the example below)

                                                
                                                    struct {             // Structure declaration
                                                        int myNum;         // Member (int variable)
                                                        string myString;   // Member (string variable)
                                                      } myStructure;       // Structure variable
                                                
                                                

    To access members of a structure, use the dot syntax (.)

                                                
                                                    // Create a structure variable called myStructure
    struct {
      int myNum;
      string myString;
    } myStructure;// Assign values to members of myStructure
    myStructure.myNum = 1;
    myStructure.myString = "Hello World!";// Print members of myStructure
    cout << myStructure.myNum << "\n";
    cout << myStructure.myString << "\n";
                                                
                                                

    You can use a comma (,) to use one structure in many variables

                                                                                        
                                                    struct {
                                                        int myNum;
                                                        string myString;
                                                      } myStruct1, myStruct2, myStruct3;                                 
                                                

                                                                                        
                                                    struct myDataType { // This structure is named "myDataType"
                                                    int myNum;
                                                    string myString;
                                                  }; 
                                                
                                                                                            
                                                        myDataType myVar; 
                                                    
  20. C++ References
    C++ References
    Creating References A reference variable is a "reference" to an existing variable, and it is created with the & operator

                                    
                                        string food = "Pizza";  // food variable
    string &meal = food;    // reference to food
                                    
                                    

                                    
                                        cout << food << "\n";  // Outputs Pizza
                                        cout << meal << "\n";  // Outputs Pizza
                                    
                                    
  21. C++ Pointers
    C++ Pointers
    Creating Pointers
    You learned from the previous chapter, that we can get the memory address of a variable by using the & operator

    A pointer however, is a variable that stores the memory address as its value.

    A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer


    Get Memory Address and Value
    In the example from the previous page, we used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator)


    Note that the * sign can be confusing here, as it does two different things in our code:

    When used in declaration (string* ptr), it creates a pointer variable. When not used in declaration, it act as a dereference operator.

                                    
                                        string food = "Pizza"; // A food variable of type string                                    cout << food;  // Outputs the value of food (Pizza)
                                        cout << &food; // Outputs the memory address of food (0x6dfed4)
                                    
                                    

                                    
                                        string food = "Pizza";  // Variable declaration
                                        string* ptr = &food;    // Pointer declaration
                                        
                                        // Reference: Output the memory address of food with the pointer (0x6dfed4)
                                        cout << ptr << "\n";
                                        
                                        // Dereference: Output the value of food with the pointer (Pizza)
                                        cout << *ptr << "\n";
                                    
                                    

                                    
                                        // Change the value of the pointer
                                        *ptr = "Hamburger";
                                        
                                        // Output the new value of the pointer (Hamburger)
                                        cout << *ptr << "\n";
                                        
                                        // Output the new value of the food variable (Hamburger)
                                        cout << food << "\n";
                                    
                                    
  22. C++ Functions
    C++ Functions
    A function is a block of code which only runs when it is called.

    You can pass data, known as parameters, into a function.

    Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.


    Create a Function
    C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also create your own functions to perform certain actions.

    To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ()


    Call a Function
    Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are called.

    To call a function, write the function's name followed by two parentheses () and a semicolon ;

    In the following example, myFunction() is used to print a text (the action), when it is called


    Function Declaration and Definition
    A C++ function consist of two parts:

    Declaration: the return type, the name of the function, and parameters (if any)

    Definition: the body of the function (code to be executed)


    Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur However, it is possible to separate the declaration and the definition of the function - for code optimization.

    You will often see C++ programs that have function declaration above main(), and function definition below main(). This will make the code better organized and easier to read


    Parameters and Arguments
    Information can be passed to functions as a parameter. Parameters act as variables inside the function.

    Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma


    When a parameter is passed to the function, it is called an argument.


    Default Parameter Value
    You can also use a default parameter value, by using the equals sign (=).A parameter with a default value, is often known as an "optional parameter".


    Return Values
    The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function

                                    
                                        void myFunction() {
                                            // code to be executed
                                          }
                                    
                                    

                                    
                                        // Create a function
                                        void myFunction() {
                                          cout << "I just got executed!";
                                        }
                                        
                                        int main() {
                                          myFunction(); // call the function
                                          return 0;
                                        }
                                        
                                    
                                    

                                    
                                        // Function declaration
    void myFunction();// The main method
    int main() {
      myFunction();  // call the function
      return 0;
    }// Function definition
    void myFunction() {
      cout << "I just got executed!";
    }
                                    
                                    

                                    
                                        void functionName(parameter1, parameter2, parameter3) {
                                            // code to be executed
                                          }
                                    
                                    

                                    
                                        void myFunction(string country = "Norway") {
                                            cout << country << "\n";
                                          }
                                          
                                          int main() {
                                            myFunction("Sweden");
                                            myFunction("India");
                                            myFunction();
                                            myFunction("USA");
                                            return 0;
                                          }
                                          
                                          // Sweden
                                          // India
                                          // Norway
                                          // USA
                                    
                                    

                                    
                                        int myFunction(int x) {
                                            return 5 + x;
                                          }
                                    
                                    

                                    
                                        void swapNums(int &x, int &y) {
                                            int z = x;
                                            x = y;
                                            y = z;
                                          }
                                          
                                          int main() {
                                            int firstNum = 10;
                                            int secondNum = 20;
                                          
                                            cout << "Before swap: " << "\n";
                                            cout << firstNum << secondNum << "\n";
                                          
                                            // Call the function, which will change the values of firstNum and secondNum
                                            swapNums(firstNum, secondNum);
                                          
                                            cout << "After swap: " << "\n";
                                            cout << firstNum << secondNum << "\n";
                                          
                                            return 0;
                                          }
                                    
                                    
  23. Function Overloading
    Function Overloading
    With function overloading, multiple functions can have the same name with different parameters


    Note: Multiple functions can have the same name as long as the number and/or type of parameters are different.
                                    
                                        int plusFunc(int x, int y) {
                                            return x + y;
                                          }
                                          
                                          double plusFunc(double x, double y) {
                                            return x + y;
                                          }
                                          
                                          int main() {
                                            int myNum1 = plusFunc(8, 5);
                                            double myNum2 = plusFunc(4.3, 6.26);
                                            cout << "Int: " << myNum1 << "\n";
                                            cout << "Double: " << myNum2;
                                            return 0;
                                          }
                                    
                                    
  24. C++ Recursion
    C++ Recursion
    Recursion
    Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.


    Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.


    Recursion Example
    Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers
                                    
                                        int sum(int k) {
                                            if (k > 0) {
                                              return k + sum(k - 1);
                                            } else {
                                              return 0;
                                            }
                                          }
                                          
                                          int main() {
                                            int result = sum(10);
                                            cout << result;
                                            return 0;
                                          }
                                    
                                    
  25. C++ OOP
    C++ OOP
    OOP stands for Object-Oriented Programming.

    Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

    Object-oriented programming has several advantages over procedural programming:


    OOP is faster and easier to execute
    OOP provides a clear structure for the programs
    OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
    OOP makes it possible to create full reusable applications with less code and shorter development time


    Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.


    C++ What are Classes and Objects?
    Classes and objects are the two main aspects of object-oriented programming.

    Look at the following illustration to see the difference between class and objects


    Create an Object

    In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.

    To create an object of MyClass, specify the class name, followed by the object name.

    To access the class attributes (myNum and myString), use the dot syntax (.) on the object

    class

    Fruit

    objects

    Apple

    Banana

    Mango




    Class Methods
    Methods are functions that belongs to the class.

    There are two ways to define functions that belongs to a class:

    Inside class definition
    Outside class definition
    In the following example, we define a function inside the class, and we name it "myMethod".

    Note: You access methods just like you access attributes; by creating an object of the class and using the dot syntax (.)

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

                                    
                                        class MyClass {       // The class
                                            public:             // Access specifier
                                              int myNum;        // Attribute (int variable)
                                              string myString;  // Attribute (string variable)
                                          };
                                          
                                          int main() {
                                            MyClass myObj;  // Create an object of MyClass
                                          
                                            // Access attributes and set values
                                            myObj.myNum = 15; 
                                            myObj.myString = "Some text";
                                          
                                            // Print attribute values
                                            cout << myObj.myNum << "\n";
                                            cout << myObj.myString;
                                            return 0;
                                          }
                                    
                                    

    Inside class definition

                                    
                                        class MyClass {        // The class
                                            public:              // Access specifier
                                              void myMethod() {  // Method/function defined inside the class
                                                cout << "Hello World!";
                                              }
                                          };
                                          
                                          int main() {
                                            MyClass myObj;     // Create an object of MyClass
                                            myObj.myMethod();  // Call the method
                                            return 0;
                                          }  
                                    
                                    

    Outside class definition

                                        
                                            class MyClass {        // The class
                                                public:              // Access specifier
                                                  void myMethod();   // Method/function declaration
                                              };
                                              
                                              // Method/function definition outside the class
                                              void MyClass::myMethod() {
                                                cout << "Hello World!";
                                              }
                                              
                                              int main() {
                                                MyClass myObj;     // Create an object of MyClass
                                                myObj.myMethod();  // Call the method
                                                return 0;
                                              }  
                                        
                                        
  26. C++ Constructors
    C++ Constructors
    Constructors
    A constructor in C++ is a special method that is automatically called when an object of a class is created.


    To create a constructor, use the same name as the class, followed by parentheses ()


    Constructor Parameters
    Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.


    The following class have brand, model and year attributes, and a constructor with different parameters. Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc). When we call the constructor (by creating an object of the class), we pass parameters to the constructor, which will set the value of the corresponding attributes to the same
                                    
                                        class MyClass {     // The class
                                            public:           // Access specifier
                                              MyClass() {     // Constructor
                                                cout << "Hello World!";
                                              }
                                          };
                                          
                                          int main() {
                                            MyClass myObj;    // Create an object of MyClass (this will call the constructor)
                                            return 0;
                                          }  
                                    
                                    
                                        
                                            class Car {        // The class
                                                public:          // Access specifier
                                                  string brand;  // Attribute
                                                  string model;  // Attribute
                                                  int year;      // Attribute
                                                  Car(string x, string y, int z); // Constructor declaration
                                              };
                                              
                                              // Constructor definition outside the class
                                              Car::Car(string x, string y, int z) {
                                                brand = x;
                                                model = y;
                                                year = z;
                                              }
                                              
                                              int main() {
                                                // Create Car objects and call the constructor with different values
                                                Car carObj1("BMW", "X5", 1999);
                                                Car carObj2("Ford", "Mustang", 1969);
                                              
                                                // Print values
                                                cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
                                                cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
                                                return 0;
                                              }
                                        
                                        
  27. Access Specifiers
    Access Specifiers
    Access Specifiers
    By now, you are quite familiar with the public keyword that appears in all of our class examples


    In C++, there are three access specifiers:


    public - members are accessible from outside the class

    private - members cannot be accessed (or viewed) from outside the class

    protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
                                    
                                        class MyClass {  // The class
                                            public:        // Access specifier
                                              // class members goes here
                                          };
                                    
                                    
                                        
                                            class MyClass {
                                                public:    // Public access specifier
                                                  int x;   // Public attribute
                                                private:   // Private access specifier
                                                  int y;   // Private attribute
                                              };
                                              
                                              int main() {
                                                MyClass myObj;
                                                myObj.x = 25;  // Allowed (public)
                                                myObj.y = 50;  // Not allowed (private)
                                                return 0;
                                              }
                                        
                                        
  28. C++ Encapsulation
    C++ Encapsulation
    Encapsulation
    The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.


    Access Private Members
    To access a private attribute, use public "get" and "set" methods


    Why Encapsulation?
    1) It is considered good practice to declare your class attributes as private (as often as you can). Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts
    2)Increased security of data
                                    
                                        class Employee {
                                            private:
                                              // Private attribute
                                              int salary;
                                          
                                            public:
                                              // Setter
                                              void setSalary(int s) {
                                                salary = s;
                                              }
                                              // Getter
                                              int getSalary() {
                                                return salary;
                                              }
                                          };
                                          
                                          int main() {
                                            Employee myObj;
                                            myObj.setSalary(50000);
                                            cout << myObj.getSalary();
                                            return 0;
                                          }
                                    
                                    
  29. C++ Inheritance
    C++ Inheritance
    Inheritance
    In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories


    It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

    1) derived class (child) - the class that inherits from another class

    2) base class (parent) - the class being inherited from

    To inherit from a class, use the : symbol.
                                    
                                        // Base class
    class Vehicle {
      public:
        string brand = "Ford";
        void honk() {
          cout << "Tuut, tuut! \n" ;
        }
    };// Derived class
    class Car: public Vehicle {
      public:
        string model = "Mustang";
    };int main() {
      Car myCar;
      myCar.honk();
      cout << myCar.brand + " " + myCar.model;
      return 0;
    }
                                    
                                    

    Multilevel Inheritance

    A class can also be derived from one class, which is already derived from another class.
                                        
                                            // Base class (parent)
                                            class MyClass {
                                              public:
                                                void myFunction() {
                                                  cout << "Some content in parent class." ;
                                                }
                                            };
                                            
                                            // Derived class (child)
                                            class MyChild: public MyClass {
                                            };
                                            
                                            // Derived class (grandchild)
                                            class MyGrandChild: public MyChild {
                                            };
                                            
                                            int main() {
                                              MyGrandChild myObj;
                                              myObj.myFunction();
                                              return 0;
                                            }
                                        
                                        

    Multiple Inheritance

    A class can also be derived from more than one base class, using a comma-separated list
                                        
                                            // Base class
    class MyClass {
      public:
        void myFunction() {
          cout << "Some content in parent class." ;
        }
    };// Another base class
    class MyOtherClass {
      public:
        void myOtherFunction() {
          cout << "Some content in another class." ;
        }
    };// Derived class
    class MyChildClass: public MyClass, public MyOtherClass {
    };int main() {
      MyChildClass myObj;
      myObj.myFunction();
      myObj.myOtherFunction();
      return 0;
    }
                                        
                                        
  30. C++ Inheritance Access
    C++ Inheritance Access
    Access Specifiers
    You learned from the Access Specifiers chapter that there are three specifiers available in C++. Until now, we have only used public (members of a class are accessible from outside the class) and private (members can only be accessed within the class). The third specifier, protected, is similar to private, but it can also be accessed in the inherited class
  31. C++ Polymorphism
    C++ Polymorphism
    Polymorphism
    Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

    Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

    For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.)
                                    
                                        // Base class
    class Animal {
      public:
        void animalSound() {
          cout << "The animal makes a sound \n";
        }
    };// Derived class
    class Pig : public Animal {
      public:
        void animalSound() {
          cout << "The pig says: wee wee \n";
        }
    };// Derived class
    class Dog : public Animal {
      public:
        void animalSound() {
          cout << "The dog says: bow wow \n";
        }
    };int main() {
      Animal myAnimal;
      Pig myPig;
      Dog myDog;  myAnimal.animalSound();
      myPig.animalSound();
      myDog.animalSound();
      return 0;
    }
                                    
                                    
  32. C++ Files
    C++ Files
    The fstream library allows us to work with files.
    To use the fstream library, include both the standard <iostream> AND the <fstream> header file
    Class Description
    ofstream Creates and writes to files
    ifstream Reads from files
    fstream A combination of ofstream and ifstream: creates, reads, and writes to files

                                    
                                        #include <iostream>
                                        #include <fstream>
                                    
                                    

                                    
                                        int main() {
                                            // Create and open a text file
                                            ofstream MyFile("filename.txt");
                                          
                                            // Write to the file
                                            MyFile << "Files can be tricky, but it is fun enough!";
                                          
                                            // Close the file
                                            MyFile.close();
                                          }   
                                    
                                    

                                        
                                            // Create a text string, which is used to output the text file
                                            string myText;
                                            
                                            // Read from the text file
                                            ifstream MyReadFile("filename.txt");
                                            
                                            // Use a while loop together with the getline() function to read the file line by line
                                            while (getline (MyReadFile, myText)) {
                                              // Output the text from the file
                                              cout << myText;
                                            }
                                            
                                            // Close the file
                                            MyReadFile.close();
                                        
                                        
  33. C++ Exceptions
    C++ Exceptions
    When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

    When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error).


    C++ try and catch
    Exception handling in C++ consist of three keywords: try, throw and catch:


    The try statement allows you to define a block of code to be tested for errors while it is being executed.


    The throw keyword throws an exception when a problem is detected, which lets us create a custom error.


    The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
                                    
                                        try {
                                            // Block of code to try
                                            throw exception; // Throw an exception when a problem arise
                                          }
                                          catch () {
                                            // Block of code to handle errors
                                          }
                                    
                                    

    Handle Any Type of Exceptions (...)

                                        
                                            try {
                                                int age = 15;
                                                if (age >= 18) {
                                                  cout << "Access granted - you are old enough.";
                                                } else {
                                                  throw 505;
                                                }
                                              }
                                              catch (...) {
                                                cout << "Access denied - You must be at least 18 years old.\n";
                                              }