cppnotes
cppnotes
Disha
C++ Introduction
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
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.
C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
C++ Syntax
Let's break up the following code to understand it better:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
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 appear in a C++ program, is int main(). This
is called a function. Any code inside its curly brackets {} will be executed.
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 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:
Example
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
It is up to you if you want to include the standard namespace library or not.
#include <iostream>
int main() {
return 0;
}
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:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
New Lines
To insert a new line, you can use the \n character:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
int main() {
return 0;
Both \n and endl are used to break lines. However, \n is most used.
#include <iostream>
return 0;
#include <iostream>
int main() {
return 0;
#include <iostream>
int main() {
return 0;
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).
Example
#include <iostream>
int main() {
// This is a comment
return 0;
Example
#include <iostream>
int main() {
return 0;
Example
#include <iostream>
using namespace std;
int main() {
return 0;
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords),
for example:
Syntax
type variableName = 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:
Example
Create a variable called myNum of type int and assign it the value 15:
#include <iostream>
int main() {
return 0;
You can also declare a variable without assigning the value, and assign the
value later:
Example
#include <iostream>
int main() {
int myNum;
myNum = 15;
return 0;
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
#include <iostream>
using namespace std;
int main() {
return 0;
Other Types
A demonstration of other data types:
Example
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
You will learn more about the individual types in the Data Types chapter.
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:
Example
#include <iostream>
cout << "I am " << myAge << " years old.";
return 0;
Example
#include <iostream>
int main() {
int x = 5;
int y = 6;
int sum = x + y;
return 0;
Example
#include <iostream>
int main() {
int x = 5, y = 6, z = 50;
cout << x + y + z;
return 0;
Example
#include <iostream>
int main() {
int x, y, z;
x = y = z = 50;
cout << x + y + z;
return 0;
C++ Identifiers
All C++ variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Example
#include <iostream>
// Good name
int m = 60;
cout << m;
return 0;
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):
Example
#include <iostream>
int main() {
return 0;
You should always declare the variable as constant when you have values that
are unlikely to change:
Example
#include <iostream>
int main() {
return 0;
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:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
#include <iostream>
int main() {
int x;
cout << "Type a number: "; // Type a number and press enter
return 0;
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 (>>)
Example
#include <iostream>
int x, y;
int sum;
cin >> x;
cin >> y;
sum = x + y;
return 0;
#include <iostream>
#include <string>
int main () {
// Creating variables
return 0;
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for st
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for st
You will learn more about the individual data types in the next chapters.
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.
int
#include <iostream>
int main () {
return 0;
float
#include <iostream>
int main () {
return 0;
double
#include <iostream>
int main () {
double myNum = 19.99;
return 0;
The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it is
safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Example
#include <iostream>
int main () {
float f1 = 35e3;
double d1 = 12E4;
return 0;
Boolean Types
A boolean data type is declared with the bool keyword and can only take the
values true or false.
int main() {
return 0;
Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.
Character Types
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
#include <iostream>
int main () {
return 0;
int main () {
cout << a;
cout << b;
cout << c;
return 0;
String Types
The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
#include <iostream>
#include <string>
int main() {
You will learn more about strings, in our C++ Strings Chapter.
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:
Example
#include <iostream>
int main() {
cout << x;
return 0;
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:
Example
#include <iostream>
int main() {
return 0;
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic
operators are
Operator Name Description Example used to perform
common
mathematical
operations.
+ Addition Adds together two values x+y
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:
Example
#include <iostream>
int main() {
int x = 10;
cout << x;
return 0;
Example
#include <iostream>
int main() {
int x = 10;
x += 5;
cout << x;
return 0;
+= 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.
In the following example, we use the greater than operator (>) to find out if 5 is
greater than 3:
Example
#include <iostream>
int main() {
int x = 5;
int y = 3;
return 0;
!= Not equal x != y
You will learn much more about comparison operators and how to use them in a
later chapter.
Logical Operators
As with comparison operators, you can also test for true (1) or false (0) values
with logical operators.
Logical operators are used to determine the logic between variables or values:
&& 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 !(x < 5 && x < 10)
true
You will learn much more about true and false values in a later chapter.
C++ Strings
Strings are used for storing text.
Example
Create a variable of type string and assign it a value:
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
#include <iostream>
#include <string>
int main() {
String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:
Example
#include <iostream>
#include <string>
int main () {
return 0;
Example
#include <iostream>
#include <string>
return 0;
Append
A string in C++ is actually an object, which contain functions that can perform
certain operations on strings. For example, you can also concatenate strings
with the append() function:
Example
#include <iostream>
#include <string>
int main () {
return 0;
}
Example
#include <iostream>
int main () {
int x = 10;
int y = 20;
int z = x + y;
cout << z;
return 0;
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
#include <iostream>
#include <string>
int main () {
string x = "10";
string y = "20";
string z = x + y;
cout << z;
return 0;
String Length
To get the length of a string, use the length() function:
Example
#include <iostream>
#include <string>
int main() {
cout << "The length of the txt string is: " << txt.length();
return 0;
}
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():
Example
#include <iostream>
#include <string>
int main() {
cout << "The length of the txt string is: " << txt.size();
return 0;
Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].
Example
#include <iostream>
#include <string>
int main() {
string myString = "Hello";
return 0;
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
Example
#include <iostream>
#include <string>
int main() {
return 0;
// Outputs e
#include <string>
int main() {
myString[0] = 'J';
return 0;
string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
#include <iostream>
int main() {
string txt = "We are the so-called \"Vikings\" from the north.";
return 0;
Example
#include <iostream>
int main() {
string txt = "It\'s alright.";
return 0;
Example
#include <iostream>
int main() {
return 0;
\n New Line
\t Tab
User Input Strings
It is possible to use the extraction operator >> on cin to store a string entered by
a user:
Example
User Input Strings
It is possible to use the extraction operator >> on cin to store a string entered by
a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
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:
Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
#include <iostream>
#include <string>
int main() {
string fullName;
return 0;
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 string (and cout) objects:
Example
#include <iostream>
#include <string>
int main() {
return 0;
C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
Example
#include <iostream>
int main() {
return 0;
And the min(x,y) function can be used to find the lowest value of x and y:
Example
#include <iostream>
int main() {
cout << min(5, 10);
return 0;
Example
// Include the cmath library
#include <iostream>
#include <cmath>
int main() {
return 0;
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:
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
#include <iostream>
int main() {
return 0;
from the example above, you can read that a true value returns 1,
and false returns 0.
Boolean Expression
A Boolean expression returns a boolean value that is either 1 (true)
or 0 (false).
You can use a comparison operator, such as the greater than (>) operator, to
find out if an expression (or variable) is true or false:
Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
#include <iostream>
int main() {
int x = 10;
int y = 9;
return 0;
Or even easier:
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
#include <iostream>
int main() {
return 0;
#include <iostream>
int main() {
int x = 10;
return 0;
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal
to 15
In the example below, we use the >= comparison operator to find out if the age
(25) is greater than OR equal to the voting age limit, which is set to 18:
Example
int myAge = 25;
int votingAge = 18;
#include <iostream>
using namespace std;
int main() {
cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are
allowed to vote!
return 0;
Cool, right? An even better approach (since we are on a roll now), would be to
wrap the code above in an if...else statement, so we can perform different
actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18.
Otherwise output "Not old enough to vote.":
#include <iostream>
int main() {
return 0;
Booleans are the basis for all C++ comparisons and conditions.
You will learn more about conditions (if...else) in the next chapter.
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of C++ code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
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
#include <iostream>
int main() {
return 0;
Example
#include <iostream>
int main() {
int x = 20;
int y = 18;
if (x > y) {
return 0;
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".
Syntax
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
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
#include <iostream>
int main() {
} else {
return 0;
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".
Syntax
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
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
#include <iostream>
int main() {
} else {
return 0;
}
Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
#include <iostream>
int main() {
} else {
cout << "Good evening.";
return 0;
Example
#include <iostream>
#include <string>
int main() {
return 0;
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
#include <iostream>
int main() {
int day = 4;
switch (day) {
case 1:
break;
case 2:
break;
case 3:
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
return 0;
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.
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:
Example
#include <iostream>
int main() {
int day = 4;
switch (day) {
case 6:
break;
case 7:
break;
default:
return 0;
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.
Syntax
while (condition) {
// code block to be executed
}
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:
Example
#include <iostream>
int main() {
int i = 0;
while (i < 5) {
i++;
return 0;
}
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Syntax
do {
// code block to be executed
}
while (condition);
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:
Example
#include <iostream>
int main() {
int i = 0;
do {
i++;
return 0;
}
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!
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:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
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:
Example
#include <iostream>
int main() {
return 0;
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":
Example
#include <iostream>
int main() {
// Outer loop
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
return 0;
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in an array, using a "for-each loop":
Example
#include <iostream>
int main() {
return 0;
Example
#include <iostream>
int main() {
if (i == 4) {
break;
return 0;
}
#include <iostream>
int main() {
if (i == 4) {
break;
return 0;
Break Example
#include <iostream>
int main() {
int i = 0;
if (i == 4) {
break;
return 0;
Continue Example
#include <iostream>
int main() {
int i = 0;
if (i == 4) {
i++;
continue;
i++;
return 0;
}
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:
string cars[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:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
#include <iostream>
#include <string>
using namespace std;
int main() {
return 0;
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
#include <iostream>
#include <string>
int main() {
cars[0] = "Opel";
return 0;
}
Example
#include <iostream>
#include <string>
int main() {
return 0;
This example outputs the index of each element together with its value:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
return 0;
o/p
0 = Volvo
1 = BMW
2 = Ford
3 = Mazda
4 = Tesla
Example
#include <iostream>
int main() {
}
return 0;
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in an array, using a "for-each loop":
Example
#include <iostream>
int main() {
return 0;
}
Omit Array Size
In C++, you don't have to specify the size of the array. The compiler is smart
enough to determine the size of the array based on the number of inserted
values:
Example
#include <iostream>
#include <string>
int main() {
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
return 0;
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result:
20
#include <iostream>
int main() {
return 0;
}
Why did the result show 20 instead of 5, when the array contains 5 elements?
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:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
Result:
#include <iostream>
int main() {
return 0;
However, by using the sizeof() approach from the example above, we can now
make loops that work for arrays of any size, which is more sustainable.
Instead of writing:
It is better to write:
Example
#include <iostream>
int main() {
return 0;
Example
#include <iostream>
return 0;
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:
string letters[2][4];
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.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
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:
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
This statement accesses the value of the element in the first row (0) and third
column (2) of the letters array.
Example
#include <iostream>
int main() {
string letters[2][4] = {
};
cout << letters[0][2];
return 0;
Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Example
#include <iostream>
int main() {
string letters[2][4] = {
};
letters[0][0] = "Z";
return 0;
}
Example
#include <iostream>
int main() {
string letters[2][4] = {
};
return 0;
}
This example shows how to loop through a three-dimensional array:
Example
#include <iostream>
int main() {
string letters[2][2][2] = {
{ "A", "B" },
{ "C", "D" }
},
{ "E", "F" },
{ "G", "H" }
};
}
}
return 0;
Example
#include <iostream>
int main() {
bool ships[4][4] = {
{ 0, 1, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
};
// 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
if (ships[row][column]) {
ships[row][column] = 0;
hits++;
// Tell the player that they have hit a ship and how many ships are left
} else {
numberOfTurns++;
cout << "You won in " << numberOfTurns << " turns";
return 0;
o/p===:-
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 1
Miss
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 2
Hit! 3 left.
Selecting coordinates
Choose a row number between 0 and 3: 2
Choose a column number between 0 and 3: 2
Miss
Selecting coordinates
Choose a row number between 0 and 3: 3
Choose a column number between 0 and 3: 2
Hit! 2 left.
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 2
Hit! 1 left.
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 0
Miss
Selecting coordinates
Choose a row number between 0 and 3: 0
Choose a column number between 0 and 3: 1
Hit! 0 left.
Victory!
You won in 7 turns
Process returned 0 (0x0) execution time : 24.994 s
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):
Example
Assign data to members of a structure and print it:
#include <iostream>
#include <string>
int main() {
struct {
int myNum;
string myString;
} myStructure;
myStructure.myNum = 1;
return 0;
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3; // Multiple structure variables
separated with commas
Example
Use one structure to represent two cars:
#include <iostream>
#include <string>
using namespace std;
int main() {
struct {
string brand;
string model;
int year;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year <<
"\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<
"\n";
return 0;
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:
myDataType myVar;
Example
Use one structure to represent two cars:
#include <iostream>
#include <string>
struct car {
string brand;
string model;
int year;
};
int main() {
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year <<
"\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<
"\n";
return 0;
}
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:
Example
string food = "Pizza";
string &meal = food;
#include <iostream>
#include <string>
int main() {
return 0;
}
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.
To access it, use the & operator, and the result will represent where the variable
is stored:
Example
string food = "Pizza";
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
Note: The memory address is in hexadecimal form (0x..). Note that you may not
get the same result in your program.
Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable by using the & operator:
Example
string food = "Pizza"; // A food variable of type string
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
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
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // A string variable
string* ptr = &food; // A pointer variable that stores the
address of food
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.
Tip: There are three ways to declare pointer variables, but the first way is
preferred:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
Note that the * sign can be confusing here, as it does two different things in our
code:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
string* ptr = &food;
Functions
A function is a block of code which only runs when it is called.
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.
Syntax
void myFunction() {
// code to be executed
}
Example Explained
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:
Example
Inside main, call myFunction():
/ Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
Example
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
Declaration: the return type, the name of the function, and parameters
(if any)
Definition: the body of the function (code to be executed)
void myFunction() { // declaration
// the body of the function (definition)
}
Example
#include <iostream>
using namespace std;
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}O/P
In function 'int main()':
5:3: error: 'myFunction' was not declared in this scope
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:
Example
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Function Parameters
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:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
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:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
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.
If we call the function without an argument, it uses the default value ("Norway"):
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
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.
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
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.
Example
#include <iostream>
using namespace std;
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
Example
#include <iostream>
using namespace std;
int main() {
cout << myFunction(5, 3);
return 0;
}
You can also store the result in a variable:
Example
#include <iostream>
using namespace std;
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
Functions - Pass By
Reference
Pass By Reference
In the examples from the previous page, we used normal variables when we
passed parameters to a function. You can also pass a reference to the function.
This can be useful when you need to change the value of the arguments:
Example
#include <iostream>
using namespace std;
int main() {
int firstNum = 10;
int secondNum = 20;
swapNums(firstNum, secondNum);
return 0;
}
O/P
Before swap:
1020
After swap:
2010
Example
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
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]).
Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:
Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of
different type:
Example
#include <iostream>
using namespace std;
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Instead of defining two functions that should do the same thing, it is better to
overload one.
Example
#include <iostream>
using namespace std;
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Note: Multiple functions can have the same name as long as the number and/or type of parameters
are different.
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
#include <iostream>
using namespace std;
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;
}
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.
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.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and
functions from the class.
You will learn much more about classes and objects in the next chapter.
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
Attributes and methods are basically variables and functions that belongs to
the class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
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. You will learn more about access specifiers later.
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:
Example
Create an object called "myObj" and access the attributes:
#include <iostream>
#include <string>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects
You can create multiple objects of one class:
Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<
"\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<
"\n";
return 0;
}
Class Methods
Methods are functions that belongs to the class.
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 ( .):
Inside Example
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;
}
---------------------------------------------
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
To define a function outside the class definition, you have to declare it inside the
class and then define it outside of the class. This is done by specifiying the
name of the class, followed the scope resolution :: operator, followed by the
name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
You can also add parameters:
Example
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj;
cout << myObj.speed(200);
return 0;
}
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 ():
Example
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;
}
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}
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 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:
Example
#include <iostream>
using namespace std;
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;
}
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):
Example
#include <iostream>
using namespace std;
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;
}
Access Specifiers
By now, you are quite familiar with the public keyword that appears in all of our
class examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
#include <iostream>
using namespace std;
// Print values
cout << myObj.x;
return 0;
}
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?
Example
#include <iostream>
using namespace std;
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 (x is public)
myObj.y = 50; // Not allowed (y is private)
return 0;
}O/P
error: y is private]
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,
which you will learn more about in the next chapter.
Note: By default, all members of a class are private if you don't specify an
access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
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.
Example
#include <iostream>
using namespace std;
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
#include <iostream>
using namespace std;
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example explained
The salary attribute is private, which have restricted access.
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
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
In the example below, the Car class (child) inherits the attributes and methods
from the Vehicle class (parent):
Example
#include <iostream>
#include <string>
using namespace std;
// 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.
In the following example, MyGrandChild is derived from class MyChild (which is
derived from MyClass).
Example
#include <iostream>
using namespace std;
// Parent class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Child class
class MyChild: public MyClass {
};
// Grandchild class
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:
Example
#include <iostream>
using namespace std;
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class.\n" ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
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:
Example
#include <iostream>
using namespace std;
// 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;
}
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
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.):
Example
// 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";
}
};
Remember from the Inheritance chapter that we use the : symbol to inherit from a class.
Now we can create Pig and Dog objects and override the animalSound() method:
Example
#include <iostream>
#include <string>
using namespace std;
// 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;
}
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create,
write or read files:
Class Description
fstream A combination of ofstream and ifstream: creates, reads, and writes to files
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
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:
Example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
// Create a text file
ofstream MyWriteFile("filename.txt");
// Write to the file
MyWriteFile << "Files can be tricky, but it is fun enough!";
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).
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.
Example
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Example
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
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 greater than
18), the catch block is skipped:
Example
#include <iostream>
using namespace std;
int main() {
try {
int age = 20;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
You can also use the throw keyword to output a reference number, like a
custom error number/code for organizing purposes:
Example
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw 505;
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
return 0;
}
Op=
Access denied - You must be at least 18 years old.
Error number: 505
Example
#include <iostream>
using namespace std;
int main() {
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";
}
return 0;
}