Programming Language
Programming Language
Programming Language
C++
PROGRAMMING LANGUAGE
1
1. C++ Intro
2. C++ Get Started
3. C++ Syntax
4. C++ Output
5. C++ Comments
6. C++ Variables
7. C++ User Input
8. C++ Data Types
9. C++ Operators
10. C++ Strings
11. C++ Math
12. C++ Booleans
13. C++ Conditions
14. C++ Switch
15. C++ While Loop
16. C++ For Loop
17. C++ Break/Continue
18. C++ Arrays
19. C++ Structures
20. C++ References
21. C++ Pointers
C++ Functions
1. C++ Functions 2. C++ Function Parameters
2. C++ Function Overloading 4. C++ Recursion
C++ Classes
1. C++ OOP 2. C++ Classes/Objects
3. C++ Class Methods 4. C++ Constructors
5. C++ Access Specifiers 6. C++ Encapsulation
7. C++ Inheritance 8. C++ Polymorphism
9. C++ Files 10. C++ Exceptions
2
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++ is portable and can be used to develop applications that can be adapted
to multiple platforms.
The main difference between C and C++ is that C++ support classes and
objects, while C does not.
3
Get Started
This tutorial will teach you the basics of C++.
There are many text editors and compilers to choose from. In this tutorial,
we will use an IDE (see below).
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all
free, and they can be used to both edit and debug C++ code.
C++ Quickstart
Let's create our first C++ file.
4
Write the following C++ code and save the file as myfirstprogram.cpp (File >
Save File as):
myfirstprogram.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Congratulations! You have now written and executed your first C++
program.
myfirstprogram.cpp
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Result:
Hello World!
C++ Syntax
C++ Syntax
Let's break up the following code to understand it better:
5
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; }
Line 7: Do not forget to add the closing curly bracket } to actually end the
main function.
6
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;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
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!";
7
cout << "I am learning C++";
return 0;
}
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;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
8
return 0;
}
Both \n and endl are used to break lines. However, \n is most used.
C++ Comments
C++ Comments
Comments can be used to explain C++ code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.
Single-line Comments
Single-line comments start with two forward slashes ( //).
Any text between // and the end of the line is ignored by the compiler (will
not be executed).
9
Example
// This is a comment
cout << "Hello World!";
Example
cout << "Hello World!"; // This is a comment
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
C++ Variables
Variables are containers for storing data values.
10
string - stores text, such as "Hello World". String values are
surrounded by double quotes
bool - stores values with two states: true or false
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.
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite
the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Other Types
11
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
int myAge = 35;
cout << "I am " << myAge << " years old.";
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
12
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;
C++ Identifiers
C++ Identifiers
All C++ variables must be identified with unique names.
Example
// Good
int minutesPerHour = 60;
13
C++ Constants
Constants
When you do not want others (or yourself) to change existing variable
values, use the const keyword (this will declare the variable as "constant",
which means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values
that are unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
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
14
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
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
15
Basic Data Types
Data Type Size Description
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15
decimal digits
The data type specifies the size and type of information the variable will
store:
You will learn more about the individual data types in the next chapters.
Float
float myNum = 5.75;
cout << myNum;
16
Double
double myNum = 19.99;
cout << myNum;
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
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.
17
Example
char myGrade = 'B';
cout << myGrade;
Alternatively, you can use ASCII values to display certain characters:
Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
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 the string library
#include <string>
You will learn more about strings, in our C++ Strings Chapter.
C++ Operators
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:
18
Example
int x = 100 + 50;
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
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
19
++ Increment Increases the value of a variable by 1 ++x
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
20
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
21
Operator Name Example
== Equal to x == y
!= Not equal x != y
You will learn much more about comparison operators and how to use them
in a later chapter.
22
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true
You will learn much more about true and false values in a later chapter.
C++ Strings
C++ Strings
Strings are used for storing text.
A string variable contains a collection of characters surrounded by double
quotes:
Example
Create a variable of type string and assign it a value:
string greeting = "Hello";
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
// Include the string library
#include <string>
// Create a string variable
string greeting = "Hello";
23
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
In the example above, we added a space after firstName to create a space
between John and Doe on output. However, you could also add a space with
quotes (" " or ' '):
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
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
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
24
Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
Example
string x = "10";
int y = 20;
string z = x + y;
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
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
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
25
This example prints the first character in myString:
Example
string myString = "Hello";
cout << myString[0];
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
Example
string myString = "Hello";
cout << myString[1];
// Outputs e
Example
string myString = "Hello";
myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello
string txt = "We are the so-called "Vikings" from the north.";
26
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
string txt = "We are the so-called \"Vikings\" from the north.";
Example
string txt = "The character \\ is called backslash.";
27
\n New Line
\t Tab
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
28
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;
// Type your full name: John Doe
// Your name is: John Doe
Example
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
C++ Math
C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
29
Example
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);
Example
// Include the cmath library
#include <cmath>
cout << sqrt(64);
cout << round(2.6);
cout << log(2);
Function Description
30
expm1(x) Returns ex -1
C++ Booleans
C++ Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:
YES / NO
31
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)
From the example above, you can read that a true value returns 1,
and false returns 0.
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
Or even easier:
32
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is
equal to 10
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal to
15
Example
int myAge = 25;
int votingAge = 18;
cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds
are allowed to vote!
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.":
int myAge = 25;
int votingAge = 18;
33
}
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
}
34
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
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
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".
C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the
condition is false.
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) {
35
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
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".
C++ Else If
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
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."
36
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
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
C++ Switch
37
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed.
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
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
38
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
39
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
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
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:
40
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
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
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Example explained
41
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
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
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
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}
Syntax
42
for (type variableName : arrayName) {
// code block to be executed
}
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
Note: Don't worry if you don't understand the example above. You will learn
more about arrays in the C++ Arrays chapter.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
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.
43
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
Continue Example
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
C++ Arrays
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
44
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
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
45
C++ Arrays and Loops
Loop Through an Array
You can loop through the array elements with the for loop.
Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
This example outputs the index of each element together with its value:
Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
46
The following example outputs all elements in an array, using a "for-
each loop":
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
Example
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
47
To get the size of an array, you can use the sizeof() operator:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result: 20
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: 55
Instead of writing:
It is better to write:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
48
cout << myNumbers[i] << "\n";
}
Note that, in C++ version 11 (2011), you can also use the "for-each" loop:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
It is good to know the different ways to loop through an array, since you
may encounter them all in different programs.
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" }
};
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
49
{ "G", "H" }
}
};
This statement accesses the value of the element in the first row
(0) and third column (2) of the letters array.
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Remember that: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
50
array's dimensions.
The following example outputs all elements in the letters array:
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Example
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
51
Example
// We put "1" to indicate there is a ship.
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
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";
}
52
numberOfTurns++;
}
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.
Example
Assign data to members of a structure and print it:
// Create a structure variable called myStructure
struct {
int myNum;
string myString;
} myStructure;
53
myStructure.myString = "Hello World!";
Example
Use one structure to represent two cars:
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a
comma here
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.
54
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:
// Declare a structure named "car"
struct car {
string brand;
string model;
int year;
};
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
55
Creating References
A reference variable is a "reference" to an existing variable, and it is created
with the & operator:
Example
string food = "Pizza";
string &meal = food;
To access it, use the & operator, and the result will represent where the
variable is stored:
Example
string food = "Pizza";
Note: The memory address is in hexadecimal form (0x..). Note that you may
not get the same result in your program.
56
And why is it useful to know the memory address?
References and Pointers (which you will learn about in the next chapter)
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:
Example
string food = "Pizza"; // A food variable of type string
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
string food = "Pizza"; // A food variable of type string
string* ptr = &food; // A pointer variable, with the name ptr, that
stores the address of food
57
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:
C++ Dereference
Get Memory Address and Value
In the example from the previous page, we used the pointer variable to get
the memory address of a variable (used together with
the & reference operator). However, you can also use the pointer to get the
value of the variable, by using the * operator (the dereference operator):
Example
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:
58
C++ Modify Pointers
Modify the Pointer Value
You can also change the pointer's value. But note that this will also change
the value of the original variable:
Example
string food = "Pizza";
string* ptr = &food;
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
C++ 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.
59
To create (often referred to as declare) a function, specify the name of the
function, followed by parentheses ():
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.
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
60
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
61
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 // F
unction declaration
void myFunction();
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
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
62
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}
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.
63
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
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
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
64
This example returns the sum of a function with two parameters:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
65
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
66
Example Explained
The function (myFunction) takes an array as its parameter (int
myNumbers[5]), and loops through the array elements with the for loop.
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]).
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
int plusFuncInt(int x, int y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
67
return 0;
}
Instead of defining two functions that should do the same thing, it is better
to overload one.
Example
int plusFunc(int x, int y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
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
68
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
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:+ 9
+ 83 + 2 + 1 + 0Since 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.
69
Object-oriented programming has several advantages over procedural
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 objects
Fruit Apple
Banana
Mango
Another example:
Class objects
Car Audi
Volvo
Toyota
70
C++ Classes and Objects
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.
71
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:
int main() {
MyClass myObj; // Create an object of MyClass
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;
72
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
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
73
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;
}
Parameters
You can also add parameters:
Example
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
74
return 0;
}
C++ Constructors
Constructors
A constructor in C++ is a special method that is automatically called when
an object of a class is created.
To create a constructor, use the same name as the class, followed by
parentheses ():
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;
}
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
class Car { // The class
public: // Access specifier
75
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
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
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
76
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;
}
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
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.
77
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
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
};
C++ Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside the class). If
you want others to read or modify the value of a private member, you can
provide public get and set methods.
78
Access Private Members
To access a private attribute, use public "get" and "set" methods:
Example
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example explained
Why Encapsulation?
It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better control of
79
your data, because you (or others) can change one part of the code
without affecting other parts
Increased security of data
C++ Inheritance
Inheritance
In C++, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:
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
// 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;
}
80
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.
Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
81
A class can also be derived from more than one base class, using a comma-
separated list:
Example
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
82
};
// 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
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.):
83
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
// 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
84
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
C++ Files
The fstream library allows us to work with files.
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
85
Ofstream Creates and writes to files
Fstream A combination of ofstream and ifstream: creates, reads, and writes to files
Example
#include <iostream>
#include <fstream>
using namespace std;
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.
86
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
// Create a text string, which is used to output the text file
string myText;
// Use a while loop together with the getline() function to read the
file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
C++ Exceptions
C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw an exception (throw
an error).
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
87
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
Example
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Example
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;
}
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.
88
Example
int age = 20;
You can also use the throw keyword to output a reference number, like a
custom error number/code for organizing purposes:
Example
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;
}
Example
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";
}
89