Computer Programming 1 - C++ PDF
Computer Programming 1 - C++ PDF
Programming 1
C++
What is 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.
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++ supports classes and objects, while C does not.
Note: Web-based IDE's can work as well, but functionality is limited. We will use Code::Blocks in
our tutorial, which we believe is a good place to start. You can find the latest version of Codeblocks
at http://www.codeblocks.org/. Download the mingw-setup.exe file, which will install the text editor
with a compiler.
C++ Quickstart
● Let's create our first C++ file. Open Codeblocks and go to File > New > Empty File.
● Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how
to run the code. In Codeblocks, it should look like this:
● Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:
C++ Syntax
Example explained
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 appears 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 ;.
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.
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for
some objects:
You can add as many cout objects as you want. However, note that it does not insert a new line at the end
of the output:
New Lines
To insert a new line, you can use the \n character:
Tip: Two \n characters after each other will create a blank line:
Both \n and endl are used to break lines. However, \n is most used.
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).
● This example uses a single-line comment before a line of code:
C++ Variables
Variables are containers for storing data values. In C++, there are different types of variables (defined with
different keywords), for example:
● int - stores integers (whole numbers), without decimals, such as 123 or -123
● double - stores floating point numbers, with decimals, such as 19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
● string - stores text, such as "Hello World". String values are surrounded by double quotes
● bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Where type is one of C++ types (such as int), and variableName is the name of the variable (such as x or
myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
You can also declare a variable without assigning the value, and assign the value later:
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Other Types
A demonstration of other data types:
Display Variables
● The cout object is used together with the << operator to display variables.
● To combine both text and a variable, separate them with the << operator:
Add Variables Together
To add a variable to another variable, you can use the + operator:
C++ 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:
Good To Know
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 (>>)
C++ Operators
● Operators are used to perform operations on variables and values.
● In the example below, we use the + operator to add together two 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:
C++ divides the operators into the following groups:
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Assignment Operators
● Assignment operators are used to assign values to variables.
● In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
= 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
== Equal to x==y
C++ Strings
● Strings are used for storing text.
● A string variable contains a collection of characters surrounded by double quotes:
To use strings, you must include an additional header file in the source code, the <string> library:
Append
A string in C++ is actually an object, which contains functions that can perform certain operations on
strings. For example, you can also concatenate strings with the append() function:
Tip: 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():
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:
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
This example prints the second character in myString:
● The solution to avoid this problem is to use the backslash escape character.
● The backslash (\) escape character turns special characters into string characters:
The sequence \" inserts a double quote in a string:
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it
can only display a single word (even if you type many words):
● From the example above, you would expect the program to print "John Doe", but it only prints "John".
● That's why, when working with strings, we often use the getline() function to read a line of text. It
takes cin as the first parameter, and the string variable as second:
Omitting Namespace
You might see some C++ programs that run without the standard namespace library. The using namespace
std line can be omitted and replaced with the std keyword, followed by the :: operator for string (and
cout) objects:
C++ Math
Max and min
The max(x,y) function can be used to find the highest value of x and y:
And the min(x,y) function can be used to find the lowest value of x and y:
Function Description
expm1(x) Returns ex -1
C++ Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
● YES / NO
● ON / OFF
● TRUE / FALSE
For this, C++ has a bool data type, which can take the values true (1) or false (0).
Boolean Values
A boolean variable is declared with the bool keyword and can only take the values true or false:
Boolean Expression
● A Boolean expression returns a boolean value that is either 1 (true) or 0 (false).
● This is useful to build logic, and find answers.
● You can use a comparison operator, such as the greater than (>) operator, to find out if an
expression (or variable) is true or false:
In the examples below, we use the equal to (==) operator to evaluate an expression:
Booleans are the basis for all C++ comparisons and conditions.
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the >
operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is
greater than y".
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to
the else condition and print to the screen "Good evening". If the time was less than 18, the program would
print "Good day".
Instead of writing:
A break can save a lot of execution time because it "ignores" the execution of all the rest
of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match:
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than
5:
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
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.
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example explained
● Statement 1 sets a variable before the loop starts (int i = 0).
● Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true,
the loop will start over again, if it is false, the loop will end.
● Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
This example will only print even values between 0 and 10:
Nested Loops
● It is also possible to place a loop inside another loop. This is called a nested loop.
● The "inner loop" will be executed one time for each iteration of the "outer loop":
The following example outputs all elements in an array, using a "for-each loop":
C++ Break and Continue
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.
● This example jumps out of the loop when i is equal to 4:
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. This example skips the value of 4:
We have now declared a variable that holds an array of four strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
The following example outputs all elements in an array, using a "for-each loop":
● Why did the result show 20 instead of 5, when the array contains 5 elements?
● It is because the sizeof() operator returns the size of a type in bytes.
● You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example
above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
● To find out how many elements an array has, you have to divide the size of the array by the size of
the data type it contains:
It is better to write:
Note that, in C++ version 11 (2011), you can also use the "for-each" loop:
It is good to know the different ways to loop through an array, since
you may encounter them all in different programs.
Multi-Dimensional Arrays
● A multi-dimensional array is an array of arrays.
● To declare a multi-dimensional array, define the variable type, specify the name of the array
followed by square brackets which specify how many elements the main array has, followed by
another set of square brackets which indicates how many elements the sub-arrays have:
● As with ordinary arrays, you can insert values with an array literal - a comma-separated list inside
curly braces. In a multi-dimensional array, each element in an array literal is another array literal.
● Each set of square brackets in an array declaration adds another dimension to an array. An array
like the one above is said to have two dimensions.
● Arrays can have any number of dimensions. The more dimensions an array has, the more complex
the code becomes. The following array has three dimensions:
// Keep track of how many hits the player has and how many turns they have played in
these variables
int hits = 0;
int numberOfTurns = 0;
// Allow the player to keep going until they have hit all four ships
while (hits < 4) {
int row, column;
// Tell the player that they have hit a ship and how many ships are left
cout << "Hit! " << (4-hits) << " left.\n\n";
} else {
// Tell the player that they missed
cout << "Miss\n\n";
}
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):
Access Structure Members
To access members of a structure, use the dot syntax (.):
Named Structures
● By giving a name to the structure, you can treat it as a data type. This means that you can create
variables with this structure anywhere in the program at any time.
● To create a named structure, put the name of the structure right after the struct keyword:
To declare a variable that uses the structure, use the name of the structure as the data type of the variable:
Example:
Use one structure to represent two cars:
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
return 0;
}
C++ References
Creating References
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
Now, we can use either the variable name food or the reference name meal to refer to the food variable:
Memory Address
● In the example from the previous page, the & operator was used to create a reference variable. But it
can also be used to get the memory address of a variable; which is the location of where the
variable is stored on the computer.
● When a variable is created in C++, a memory address is assigned to the variable. And when we
assign a value to the variable, it is stored in this memory address.
● To access it, use the & operator, and the result will represent where the variable is stored:
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your
program.
References and Pointers are important in C++, because they give you the ability to manipulate the data
in the computer's memory - which can reduce the code and improve the performance.
These two features are one of the things that make C++ stand out from other programming languages,
like Python and Java.
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:
Example explained
● Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk
sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're
working with.
● Use the & operator to store the memory address of the variable called food, and assign it to the
pointer.
● Now, ptr holds the value of food's memory address.
Tip: There are three ways to declare pointer variables, but the first way is preferred:
C++ Dereference
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 acts as a dereference operator.
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
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 ():
Example Explained
● myFunction() is the name of the function
● void means that the function does not have a return value. You will learn more about return values
later in the next chapter
● inside the function (the body), add code that defines what the function should do
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:
A function can be called multiple times:
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:
The following example has a function that takes a string called fname as parameter. When the function is
called, we pass along a first name, which is used inside the function to print the full name:
● When a parameter is passed to the function, it is called an argument. So, from the example above:
fname is a parameter, while Liam, Jenny and Anja are arguments.
C++ Default Parameters
Default Parameter Value
● You can also use a default parameter value, by using the equals sign (=).
● If we call the function without an argument, it uses the default value ("Norway"):
A parameter with a default value, is often known as an "optional parameter". From the example above,
country is an optional parameter and "Norway" is the default value.
Note that when you are working with multiple parameters, the function call must have the same number
of arguments as there are parameters, and the arguments must be passed in the same order.
C++ The Return Keyword
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:
Example Explained
● The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops through
the array elements with the for loop.
● When the function is called inside main(), we pass along the myNumbers array, which outputs the
array elements.
● Note that when you call the function, you only need to use the name of the array when passing it as
an argument myFunction(myNumbers). However, the full declaration of the array is needed in the
function parameter (int myNumbers[5]).
Consider the following example, which have two functions that add numbers of different type:
Instead of defining two functions that should do the same thing, it is better to overload one. In the example
below, we overload the plusFunc function to work for both int and double:
Note: Multiple functions can have the same name as long as the number and/or type of parameters are different.
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:
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns
the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. However, when
written correctly recursion can be a very efficient and mathematically-elegant approach to
programming.
C++ OOP
C++ What is 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.
Class Objects
Fruit Apple
Banana
Mango
Another example:
Class Objects
Car Volvo
Audi
Toyota
Example Explained
● The class keyword is used to create a class called MyClass.
● The public keyword is an access specifier, which specifies that members (attributes and methods)
of the class are accessible from outside the class.
● Inside the class, there is an integer variable myNum and a string variable myString. When variables
are declared within a class, they are called attributes.
● At last, end the class definition with a semicolon ;.
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:
Multiple Objects
You can create multiple objects of one class:
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Parameters
You can also add parameters:
C++ 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 ():
Note: The constructor has the same name as the class, it is always public, and it does not have any return
value.
Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be useful for setting initial
values for attributes.
The following class has 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:
Just like functions, constructors can also be defined outside the class. First, declare the constructor inside
the class, and then define it outside of the class by specifying the name of the class, followed by the scope
resolution :: operator, followed by the name of the constructor (which is the same as the class):
The public keyword is an access specifier. Access specifiers define how the members (attributes and
methods) of a class can be accessed. In the example above, the members are public - which means that
they can be accessed and modified from outside the code.
However, what if we want members to be private and hidden from the outside world? 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.
In the following example, we demonstrate the differences between public and private members:
Note: It is possible to access private members of a class using a public method inside the same class.
Tip: It is considered good practice to declare your class attributes as private (as often as you can). This
will reduce the possibility of yourself (or others) to mess up the code. This is also the main ingredient of
the Encapsulation concept
Note: By default, all members of a class are private if you don't specify an access specifier:
C++ 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:
Example explained
● The salary attribute is private, which has restricted access.
● The public setSalary() method takes a parameter (s) and assigns it to the salary attribute
(salary=s).
● The public getSalary() method returns the value of the private salary attribute.
● Inside main(), we create an object of the Employee class. Now we can use the setSalary() method
to set the value of the private attribute to 50000. Then we call the getSalary() method on the object
to return the value.
Why Encapsulation?
● 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
● Increased security of data
C++ Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance
concept" into two categories:
● derived class (child) - the class that inherits from another class
● base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class
(parent):
Multilevel Inheritance
● A class can also be derived from one class, which is already derived from another class.
● In the following example, MyGrandChild is derived from class MyChild (which is derived from
MyClass).
Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:
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:
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
C++ 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.):
Now we can create Pig and Dog objects and override the animalSound() method:
// 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;
}
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:
There are three classes included in the fstream library, which are used to create, write or read files:
Create and Write To a File
● To create a file, use either the ofstream or fstream class, and specify the name of the file.
● To write to the file, use the insertion operator (<<).
Read a File
● To read from a file, use either the ifstream or fstream class, and the name of the file.
● Note that we also use a while loop together with the getline() function (which belongs to the
ifstream class) to read the file line by line, and to print the content of the file:
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.
● The try and catch keywords come in pairs
Example Explained
● We use the try block to test some code: If the age variable is less than 18, we will throw an exception,
and handle it in our catch block.
● In the catch block, we catch the error and do something about it. The catch statement takes a
parameter: in our example we use an int variable (myNum) (because we are throwing an exception
of int type in the try block (age)), to output the value of age.
● If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than 18), the catch block
is skipped:
You can also use the throw keyword to output a reference number, like a custom error number/code for
organizing purposes: