CMP212 Lecture Note
CMP212 Lecture Note
CMP212 Lecture Note
CMP212
Computer Programming II
2022
1
COURSE SYLLABUS
1. Course Code and Title: CMP212 – Computer Programming II (Programming with
C++)
2. Credit Units/Contact Hours: 3/2
3. Semester/Session: Second - 2020/2021
3. Program: 200 Level Computer Science & IT
4. Course Lecturers: Muhammad Muntasir Yakubu (CC), Mukhtar Abubakar,
Nuruddeen Sama’ila Ahmad, Yusuf Surajo and Mukhtar
Umar Shitu
5. Recommended Textbooks
This course will provide the students with a solid theoretical understanding as well as practical
skills of C++ Programming. The primary aim of the Course is to enable the students to tackle
programming problems, making good use of the C++ programming in the context of Object
Oriented method to simplify the design and implementation process.
8. Course Outline
2
Constructor, Object-Oriented Programming; Classes and Objects, Encapsulation, Inheritance,
Polymorphism, Data Hiding, C++ Files, Exceptions.
9. Assessment method
Students will be graded based on the following criteria:
a. First C.A Test: 15%
b. Second C.A Test: 15%
c. Practical Classes Assessment: 10%
d. Final exam: 60%
10. Lectures’ Schedules and the grouping
Group A: B. Sc. Computer Science and IT (Sub – Group) Muhammad M. Y
Group B: B. Sc. Computer Science Students and IT (Sub – Group) Mukhtar Abubakar
Group C: B. Sc. Applied Chemistry Students (Sub – Group) Yusuf Surajo
Group D: B. Sc. Applied Chemistry Students (Sub – Group) Mukhtar U. Shitu
Group E: B. Sc. Mathematics Nuruddeen S. A
3
INTRODUCTION
Suppose a particular person is giving travel directions to a friend, that person might explain those
directions in any one of several languages, such as English, Hausa, Yoruba, or Igbo. The
directions are the same no matter which language is used to explain them, but the manner in
which the directions are expressed is different. Furthermore, the friend must be able to
understand the language being used in order to follow the directions.
PROBLEM SOLVING
The purpose of writing a program is to solve a problem. Problem solving, in general, consists of
multiple steps:
3. Designing a solution
Although this approach applies to any kind of problem solving, it works particularly well when
developing software.
The first step, Understanding the Problem, may sound obvious, but a lack of attention to this
step has been the cause of many misguided efforts. If we attempt to solve a problem we don’t
completely understand, we often end up solving the wrong problem or at least going off on
improper tangents. We must understand the needs of the people who will use the solution. These
needs often include subtle nuances that will affect our approach to the solution.
4
After we thoroughly understand the problem, we then Break the problem into manageable
pieces and design a solution. These steps go hand in hand. A solution to any problem can rarely
be expressed as one big activity. Instead, it is a series of small cooperation tasks that interact to
perform a larger task. When developing software, we don’t write one big program. We design
separate pieces that are responsible for certain parts of the solution, subsequently integrating
them with other parts.
Our first inclination toward a solution may not be best one. We must always Consider
alternatives and refine the solution as necessary. The earlier we consider alternatives, the
easier it is to modify our approach.
Implementing the solution is the act of taking the design and putting in a usable form. When
developing a software solution to a problem, the implementation stage is the process of actually
writing the program. Too often programming is thought of a writing code. But in most cases, the
final implantation of the solution is one of the last and easiest steps. The act of designing the
program should be more interesting and creative than the process of implanting the design in a
particular programming language.
Finally, we Test our solution to find any errors that exist so that we can fix them and
improve the quality of the software. Testing efforts attempt to verify that the program correctly
represents the design, which in turn provides a solution to the problem.
WHAT IS A PROGRAM?
This section introduces you to fundamental programming concepts and levels of programming
language. The task of programming computers has been described as rewarding, challenging,
easy, difficult, fast, and slow. Actually, it is a combination of all these descriptions. Writing
complex programs to solve advanced problems can be frustrating and time-consuming, but you
can have fun along the way, especially with the rich assortment of features that programming
language has to offer.
This section also describes the concept of programming, from a program’s inception to its
execution on your computer. The most difficult part of programming is breaking the problem
into logical steps that the computer can execute.
5
Keep in mind that computers are only machines. They’re not smart; in fact, they’re quite the
opposite! They don’t do anything until they are given detailed instructions. A word processor, for
example, is a program somebody wrote—in a language such as C++—that tells your computer
exactly how to behave when you type words into it.
You are familiar with the concept of programming if you have ever followed a recipe, which is a
“program,” or a list of instructions, telling you how to prepare a certain dish. A good recipe lists
these instructions in their proper order and with enough description so you can carry out the
directions successfully, without assuming anything.
Machine language
Assembly language
Machine Language
Any computer can directly understand only its own machine language, defined by its hardware
design, machine language generally consist of string of numbers (ultimately reduced to 1s and
0s) that instruct computers to perform their most elementary operations one at a time. Machine
language are independent (a particular machine language can be used on only one type of
computer); such languages are cumbersome for humans. In order for a program to run on a
computer, it must be expressed in that computer’s machine language. Each type of CPU has its
language. For that reason, we can’t run a program specifically written for sun work station with
its Sparc processor, or IBM PC, with its Intel processor.
Each machine language instruction can accomplish only a simple task, for example, a single
machine instruction might copy a value in to a register or compare a value to zero. It might take
four separate machine language instruction to add two numbers together and to store the result.
6
However, a computer can do millions of these instructions in a second, and therefore many
simple commands can be quickly executed to accomplish complex task.
Machine language code is expressed as a series of binary digits and is extremely difficult for
humans to reads and writes. Originally, programs were entered in to the computer using switches
or some similarly tedious method. Early programmers found these techniques to be time
consuming and error prone.
Assembly Language
These problems gave rise to the use of assembly language, which replaced binary digits with
mnemonics, short English – like words that represent commands or data. It is much easier for
programmers to deal with words then with binary digits. However, an assembly language
program cannot be executed directly on a computer. It must first be translated in to machine
language.
Today, most programmers use a high – level language to write software. A high - level language
is express in English – like phrase, and thus is easier for programmers to read and write. A single
high – level language programming statements are expressed in a form approaching natural
language, far removed from the machine language that is ultimately executed. C++ is a high –
level language, C, Java, and Smalltalk.
High – level language code must be translated in to machine language in order to be executed by
a translator programs called compilers. A high – level language insulates programmers from
needing to know the underlying machine language for the processor on which they are working.
7
WHAT IS C++?
C++ is a general purpose, case-sensitive, free-form programming language that supports object
oriented, procedural programming paradigms.
C++ is a middle-level language, as it encapsulates both high and low level language features. It
supports the four major pillars of object oriented programming; Inheritance, Polymorphism,
Encapsulation, and Abstraction.
C++ is a powerful computer programming language that’s appropriate for technically oriented
people with little or no programming experience, and for experienced programmers to use in
building substantial information systems. You’re already familiar with the powerful tasks
computers perform. Using this lecture note, you will write instructions commanding computers
to perform those kinds of tasks. Software (i.e. the instructions you write) controls hardware (i.e.
computer and its peripherals). Computers process data under the control of sets of instruction
called computer programs as explained earlier – these programs guide the computer through
orderly sets of actions specified by people called computer programmers. The programs that runs
on a computer are referred to as software, in this note, you’ll learn today’s key programming
methodology that’s enhancing programmer productivity, thereby reducing software –
development cost; object – oriented programming.
8
C++ Get Started
A text editor (IDE - Integrated Development Environment) is used to edit and compile
the code. Popular IDE's include: Notepad, Notepad++, sublime text, Blocks, Eclipse, and
Visual Studio etc. These are all free, and they can be used to both edit and debug C++
code.
A compiler, like MinGW /GCC, Borland C++, Dev C++, Embracadero, Clang, Visual C+
+, Intel C++, Code Block., to translate the C++ code into a language that the computer
will understand
There are many text editors and compilers to choose from. In our lectures and practical sessions,
we will use an IDE.
We will use Borland C++ or Dev C++ in our tutorial, which we believe is a good place to start.
To give C++ programming instructions to your computer as we are explaining, you need an
editor and a C++ compiler. An editor is similar to a word processor; it is a program that enables
you to type a C++ program into memory, make changes (such as typing, moving, copying,
inserting, and deleting text), and save the program more permanently in a disk file, save the
program/file as “program/file.cpp”, because C++ programs are saved with
extensions .C, .cc, .cpp, .cxx depending on the platform you are working upon. After using the
editor to type and save the program, you must compile it before you can run it. The C++
programming language is called a compiled language.
You cannot write a C++ program and run it on your computer unless you have a C++ compiler.
This compiler takes your C++ language instructions and translates them into a form that your
computer can read. A C++ compiler is the tool your computer uses to understand the C++
language instructions in your programs. Many compilers come with their own built-in editor. If
yours does, you probably feel that your C++ programming is more integrated.
To some beginning programmers, the process of compiling a program before running it might
seem like an added and meaningless step. If you know the BASIC programming language, you
might not have heard of a compiler or understand the need for one. That’s because BASIC (also
APL and some versions of other computer languages) is not a compiled language, but an
9
interpreted language. Instead of translating the entire program into machine-readable form (as a
compiler does in one step), an interpreter translates each program instruction—then executes it—
before translating the next one.
The difference between the two is subtle, but the bottom line is not; Compilers produce much
more efficient and faster-running programs than interpreters do. This seemingly extra step of
compiling is worth the effort (and with today’s compilers, there is not much extra effort needed).
Because computers are machines that do not think, the instructions you write in C++ must be
detailed. You cannot assume your computer understands what to do if some instruction is not in
your program, or if you write an instruction that does not conform to C++ language
requirements.
As object-oriented analysis, design, and programming began to catch on, Bjarne Stroustrup took
the most popular language for commercial software development, C, and extended it to provide
the features needed to facilitate object-oriented programming. He created C++ in the early 1980s,
and in less than a decade it has gone from being used by only a handful of developers at AT&T
to being the programming language of choice for an estimated one million developers
worldwide. It is expected that by the end of the decade, C++ will be the predominant language
for commercial software development.
C++ is a difficult language for at least two reasons: it inherits from the C language an economy
of expression that novices often find cryptic. And an object – oriented language, its widespread
use of classes and templates presents a challenge to those who have not thought in those terms
before.
C++ FEATURES
C++ is object oriented programming language. It provides a lot features that are given below:
Simple: C++ is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library function, data types etc.
Machine Independent or Portable: Unlike assembly language, C++ programs can be
executed in many machines with little bit or no change. But it is not platform –
independent.
10
Mid – level programming Language: C++ is also used to do low level programming, it
is used to developed system applications such as kernel, drivers etc. It also supports the
feature of high level language. That is why it is known as mid-level language
Structured Programming Language: C++ is a structured programming language in the
sense that we can break the prog`ram into parts using functions. So, it is easy to
understand and modify.
Rich Library: C++ provides a lot inbuilt functions that make the development fast.
Memory Management: It supports the feature of dynamic memory allocation. In C++
language, we can free the allocated memory at any time by calling the free() function
Speed: The compilation and execution time of C++ language is fast
Pointers: C++ provides the feature of pointer. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures, functions, arrays etc.
Recursion: In C++, we can call a function within the function program; this provides
code reusability for every function.
Extensible: C++ language is extensible because it can easily adopt new features.
Object – Oriented: C++ is object oriented programming language. OOPs makes
development and maintenance easier whereas in procedure – oriented programming,
language it is not easy to manage if code grows as project size grows.
Compiler based: C++ is a compiler based programming language, it means without
compilation no C++ program can be executed. First we need to compile our program
using compiler and then we can execute our program.
Several special purpose programs are needed to help with the process of developing new
programs. They are sometimes called software tools because they are used to build programs.
Examples of basic software tool include an editor, a compiler, and an interpreter.
Initially, you use editors as you type a program in to computer and store it in file. There are
many different editors with many different features. You should become familiar with editor you
will use regularly because it can dramatically affect the speed at which you enter and modify
your programs.
Each time you need to make a change to the code of your program, you open it in an editor, after
editing and saving your program, you attempt to translate it from high – level code in to a form
that can be executed. That translation may result in errors, in which case you return to the editor
to make changes to the code to fix the problems. Once the translation occurs successfully, you
can execute the program and evaluate the results. If the results are not what you want, you again
return to the editor to make changes.
The translation of source code in to (ultimately) machine language for particular type of CPU
can occur in variety of ways.
11
A compiler is a program that translates code in one language to equivalent code in another
language. The original code is called source code, and the language in to which it is translated is
called the target language. For many traditional compilers, the source code is translated directly
into a particular machine language. In that case, the translation process occurs once, and the
resulting executable program can be run whenever needed. Some example of C++ compiler s
are: MinGW /GCC, Borland C++, Dev C++, Embracadero, Clang, Visual C++, Intel C++, Code
Block, as explained earlier.
ERRORS
Several different kinds of problems can occur in software particularly during program
development. Term computer error is often misused and varies in meaning depending on the
person using it. From the user’s point of view, anything that goes away when interacting with a
machine is often called a computer error. A computer follows the commands we give and
operates on the data we provide. If our programs are wrong or our data are inaccurate, then we
cannot expect the results to be correct. A computer phrase used to describe this situation is
“Garbage in, Garbage out.”
Runtime error
Logical error
The compiler checks to make sure you are using the correct syntax. If you have any statements
that do not conform to the syntactic rules of the language, the compiler will produce a syntax
error. The compiler also tries to find other problems, such as the used of incompatible types of
data. The syntax might be technically correct, but you are still attempting to do something that
12
the language doesn’t semantically allow. Any error identified by the compiler is called a compile
– time error. If compile - time error occurs, an executable version of the program is not created.
The second kind of problem occurs during program execution, it is called a runtime error, and
it causes the program to terminate abnormally, for example, if we attempt to divide by zero, the
program will “crash” and halt execution at that point. Because the requested operation is
undefined, the system simply abandons its attempt to continue processing your program.
The third kind of software problem is logical error. In this case, the software compiles and
executes without any complaint, but it produce incorrect results. For example, a logical error
occurs when a value is calculated incorrectly. A programmer must test the program thoroughly,
comparing the expected results to those that actually occur. When defects are found, they must
be trace back to the source of the problem in the code and corrected. The process of finding and
correcting defects in a program is called Debugging. Logical errors can manifest themselves in
many ways, and the actual root cause might be quite difficult to discover.
C++ fully supports object-oriented principles, which includes: encapsulation, data hiding
(Abstraction), inheritance, and polymorphism.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other code
defined outside the wrapper.
Data Hiding
Data hiding is the highly valued characteristic that an object can be used without the user
knowing or caring how it works internally. Just as you can use a refrigerator without knowing
how the compressor works, you can use a well-designed object without knowing about its
internal data members.
C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. Once created, a well-defined class act as a fully encapsulated
13
entity--it is used as a whole unit. The actual inner workings of the class should be hidden. Users
of a well-defined class do not need to know how the class works; they just need to know how to
use it.
Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification (that is, top-down).
For example: Inheritance is like when the engineers at Ford Motors want to build a new car, they
have two choices: They can start from scratch, or they can modify an existing model. Perhaps
their Star model is nearly perfect, but they'd like to add a turbocharger and a six-speed
transmission. The chief engineer would prefer not to start from the ground up, but rather to say,
"Let's build another Star, but let's add these additional capabilities. We'll call the new model a
Quasar." A Quasar is a kind of Star, but one with new features.
C++ supports the idea of reuse through inheritance. A new type, which is an extension of an
existing type, can be declared. This new subclass is said to derive from the existing type and is
sometimes called a derived type. The Quasar is derived from the Star and thus inherits all its
qualities, but can add to them as needed.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) occurs when there is a hierarchy of classes
and they are related by inheritance. C++ polymorphism means that a call to a member function
will cause a different function to be executed depending on the type of object that invokes the
function.
From the above example at Ford Motors, polymorphism here is when the new Quasar might
respond differently than a Star does when you press down on the accelerator. The Quasar might
engage fuel injection and a turbocharger, while the Star would simply let gasoline into its
carburetor. A user, however, does not have to know about these differences. He can just "floor
it," and the right thing will happen, depending on which car he's driving.
C++ supports the idea that different objects do "the right thing" through what is called function
polymorphism and class polymorphism. Poly means many, and morph means form.
Polymorphism refers to the same name taking many forms.
14
Quick Start
Let's create our first C++ file, Open Text editor (IDE) and go to File > New > Empty File.
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):
#include <iostream>
int main() {
return 0;
Don't worry if you don't understand the code above - we will discuss it in detail. For now, focus
on how to run the code.
Then, go to Build > Build and Run to run (execute) the program. The result will look something
to this:
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
Congratulations! You have now written and executed your first C++ program.
15
C++ Syntax
Example
1 #include <iostream>
4 int main() {
6 return 0;
7 }
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 4: Another thing that always appear in a C++ program, is int main(). This is called a
function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World".
Note: Every C++ statement ends with a semicolon;. Also the body of int main() could also been
written as:
16
Remember: The compiler ignores white spaces. However, multiple lines make 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 run without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:
Example
#include <iostream>
int main() {
return 0;
The cout object, together with the << operator, is used to output values/print text:
Example
#include <iostream>
int main() {
return 0;
17
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>
int main() {
return 0;
New Lines
Example
#include <iostream>
int main() {
return 0;
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
18
int main() {
return 0;
Example
#include <iostream>
int main() {
return 0;
Both \n and endl are used to break lines. However, \n is used more often and is the preferred
way.
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.
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
// This is a comment
19
cout << "Hello World!";
Example
Multi-line Comments
Example
Single or multi-line comments? It is up to you which you want to use. Normally, we use // for
short comments, and /* */ for longer.
Variables
Variables are containers for storing data values. In C++, there are different types of variables
(defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
Syntax
20
Where type is one of C++ types (such as int), and variable 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:
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
Other Types
Example
21
bool myBoolean = true; // Boolean (true or false)
You will learn more about the individual types in the Data Types this section.
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
cout << "I am " << myAge << " years old.";
Example
int x = 5;
int y = 6;
int sum = x + y;
To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
Identifiers
All C++ variables must be identified with unique names. These unique names are called
identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
22
Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
Example
// Good
int m = 60;
The general rules for constructing names for variables (unique identifiers) are:
Constants
When you do not want others (or yourself) to override existing variable values, use the const
keyword (this will declare the variable as "constant", which means unchangeable and read-only):
Example
You should always declare the variable as constant when you have values that are unlikely to
change:
Example
23
User Input
You have already learned that cout is used to output (print) values. Now we will use cin to get
user input. cin is a predefined variable that reads data from the keyboard with the extraction
operator (>>).
In the following example, the user can input a number, which is stored in the variable x. Then we
print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cout << "Your number is: " << x; // Display the input value
Note: 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 (>>).
In this example, the user must input two numbers. Then we print the sum by calculating (adding)
the two numbers:
Example
int x, y;
int sum;
cin >> x;
cin >> y;
sum = x + y;
24
Data Types
As explained in the Variables section, a variable in C++ must be a specified data type:
Example
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 sections.
25
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
float
double
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;
Boolean Types
A boolean data type is declared with the bool keyword and can only take the values true or false.
When the value is returned, true = 1 and false = 0.
26
Example
Boolean values are mostly used for conditional testing, 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
From the example above, you can read that a true value returns 1, and false returns 0.
Boolean Expression
A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).
You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:
27
Example
int x = 10;
int y = 9;
Or even easier:
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
In the examples below, we use the equal to (==) operator to evaluate an expression:
Example
int x = 10;
Example
Booleans are the basis for all C++ comparisons and conditions. You will learn more about
conditions (if...else) in the next section.
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
Example
28
cout << a;
cout << b;
cout << c;
Tip: A list of all ASCII values can be found in our ASCII Table Reference (find it through
Google search engine).
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
To use strings, you must include an additional header file in the source code, the <string>
library:
Example
#include <string>
You will learn more about strings, in our C++ Strings section.
Operators
Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:
29
Example
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
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
30
variable by 1
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
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
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
31
^= x ^= 3 x=x^3
Comparison Operators
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
== Equal to x == y
!= Not equal x != y
You will learn much more about comparison operators and how to use them in later sections.
Logical Operators
32
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements x < 5 && x < 10
are true
! Logical not Reverse the result, returns false if !(x < 5 && x < 10)
the result is true
Strings
Strings are used for storing text. A string variable contains a collection of characters surrounded
by double quotes:
Example
To use strings, you must include an additional header file in the source code, the <string>
library:
Example
#include <string>
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
Example
33
string firstName = "Abubakar ";
In the example above, we added a space after firstName to create a space between Abubakar and
Muntasir on output. However, you could also add a space with quotes (" " or ' '):
Example
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
It is up to you whether you want to use + or append(). The major difference between the two, is
that the append() function is much faster. However, for testing and such, it might be easier to just
use +.
C++ uses the + operator for both addition and concatenation. Numbers are added. Strings are
concatenated. If you add two numbers, the result will be a number:
Example
34
int x = 10;
int y = 20;
Example
string x = "10";
string y = "20";
Example
string x = "10";
int y = 20;
string z = x + y;
String Length
Example
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
cout << "The length of the txt string is: " << txt.size();
Access Strings
35
You can access the characters in a string by referring to its index number inside square brackets [
]. This example prints the first character in myString:
Example
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc. This
example prints the second character in myString:
Example
// Outputs e
To change the value of a specific character in a string, refer to the index number, and use single
quotes:
Example
myString[0] = 'J';
It is possible to use the extraction operator >> on cin to display a string entered by a user:
Example
36
string firstName;
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
Example
string fullName;
From the example above, you would expect the program to print "Abubakar Muntasir", but it
only prints "Abubakar".
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;
37
Omitting Namespace
You might see some C++ programs that run without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for string (and cout) objects:
Example
#include <iostream>
#include <string>
int main() {
return 0;
C++ has many functions that allow you to perform mathematical tasks on numbers.
The max(x,y) function can be used to find the highest value of x and y:
Example
And the min(x,y) function can be used to find the lowest value of x and y:
Example
38
Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm),
can be found in the <cmath> header file:
Example
#include <cmath>
A list of other popular Math functions (from the <cmath> library) can be found in the table
below:
Function Description
expm1(x) Returns ex -1
39
floor(x) Returns the value of x rounded down to its
nearest integer
You can use these conditions to perform different actions for different decisions. C++ has the
following conditional statements:
The if Statement
40
Use the if statement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
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
Example
int x = 20;
int y = 18;
if (x > 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".
41
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
} else {
Example
} else {
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".
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
} else if (condition2) {
42
// block of code to be executed if the condition1 is false and condition2 is true
} else {
Example
} else {
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."
There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often used
to replace simple if else statements:
Syntax
43
Instead of writing the above example:
} else {
Example
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
44
This is how it works:
The switch expression is evaluated once, the value of the expression is compared with the values
of each case, If there is a match, the associated block of code is executed, the break and default
keywords are optional, and will be described later in this section, the example below uses the
weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
45
cout << "Sunday";
break;
When C++ reaches a break keyword, it breaks out of the switch block. This will stop the
execution of more code and case testing inside the block. When a match is found, and the job is
done, it's time for a break. There is no need for more testing. 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 specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
break;
case 7:
break;
default:
Note: The default keyword must be used as the last statement in the switch, and it does not need
a break.
46
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.
While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
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) {
i++;
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never
end!
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do {
47
// 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
int i = 0;
do {
i++;
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
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.
48
Example
Example explained
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
Break
You have already seen the break statement used in an earlier section of this tutorial. It was used
to "jump out" of a switch statement. The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 4:
Example
if (i == 4) {
break;
49
cout << i << "\n";
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop. This example skips the value of 4:
Example
if (i == 4) {
continue;
Break Example
int i = 0;
i++;
if (i == 4) {
break;
Continue Example
int i = 0;
50
while (i < 10) {
if (i == 4) {
i++;
continue;
i++;
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:
You access an array element by referring to the index number. This statement accesses the value
of the first element in cars:
Example
// Outputs Volvo
51
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
You can loop through the array elements with the for loop. The following example outputs all
elements in the cars array:
Example
The following example outputs the index of each element together with its value:
Example
52
Omit Array Size
You don't have to specify the size of the array. But if you don't, it will only be as big as the
elements that are inserted into it:
This is completely fine. However, the problem arises if you want extra space for future elements.
Then you have to overwrite the existing values:
If you specify the size however, the array will reserve the extra space:
string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though it's only
three elements inside it
Now you can add a fourth and fifth element without overwriting the others:
cars[3] = "Mazda";
cars[4] = "Tesla";
It is also possible to declare an array without specifying the elements on declaration, and add
them later:
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
Creating References
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
53
Now, we can use either the variable name food or the reference name meal to refer to the food
variable:
Example
Memory Address
In the example from the previous page, the & operator was used to create a reference variable.
But it can also be used to get the memory address of a variable; which is the location of where
the variable is stored on the computer. When a variable is created in C++, a memory address is
assigned to the variable. And when we assign a value to the variable, it is stored in this memory
address. To access it, use the & operator, and the result will represent where the variable is
stored:
Example
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same
result in your program. And why is it useful to know the memory address?
References and Pointers (which you will learn about in the next section) 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.
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable by
using the & operator:
54
Example
A pointer however, is a variable that stores the memory address as its value. A pointer variable
points to a data type (like int or string) of the same type, and is created with the * operator. The
address of the variable you're working with is assigned to the pointer:
Example
string* ptr = &food; // A pointer variable, with the name ptr, 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. Now, ptr holds the value of food's memory address.
Tip: There are three ways to declare pointer variables, but the first way is preferred:
string *mystring;
string * mystring;
55
Dereference
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
// Reference: Output the memory address of food with the pointer (0x6dfed4)
Note that the * sign can be confusing here, as it does two different things in our code:
When used in declaration (string* ptr), it creates a pointer variable. When not used in
declaration, it act as a dereference operator.
You can also change the pointer's value. But note that this will also change the value of the
original variable:
Example
56
// Output the memory address of food (0x6dfed4)
// Access the memory address of food and output its value (Pizza)
*ptr = "Hamburger";
Functions
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions. To create (often referred to as
declare) a function, specify the name of the function, followed by parentheses ():
Syntax
void myFunction() {
// code to be executed
Example Explained
57
void means that the function does not have a return value. You will learn more about return
values later in the next section, inside the function (the body), add code that defines what the
function should do.
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called. To call a function, write the function's name followed by
two parentheses () and a semicolon;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
// Create a function
void myFunction() {
int main() {
return 0;
Example
void myFunction() {
int main() {
58
myFunction();
myFunction();
myFunction();
return 0;
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
Note: If a user-defined function, such as myFunction() is declared after the main() function, an
error will occur. It is because C++ works from top to bottom; which means that if the function is
not declared above main(), the program is unaware of it:
Example
int main() {
myFunction();
return 0;
void myFunction() {
59
// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization. You will often see C++ programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
int main() {
return 0;
// Function definition
void myFunction() {
Function Parameters
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
// code to be executed
60
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
int main() {
myFunction("Abubakar");
myFunction("Umar");
myFunction("Usman");
return 0;
// Abubakar Refsnes
// Umar Refsnes
// Usman Refsnes
When a parameter is passed to the function, it is called an argument. So, from the example
above: fname is a parameter, while Abubakar, Umar and Usman are arguments.
You can also use a default parameter value, by using the equals sign (=). If we call the function
without an argument, it uses the default value ("Norway"):
Example
int main() {
61
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
cout << fname << " Refsnes. " << age << " years old. \n";
int main() {
myFunction("Abubakar", 3);
myFunction("Umar", 14);
myFunction("Usman", 30);
return 0;
62
// Usman 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.
The void keyword, used in the previous examples, indicates that the function should not return a
value. If you want the function to return a value, you can use a data type (such as int, string, etc.)
instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
int main() {
return 0;
// Outputs 8 (5 + 3)
Example
return x + y;
int main() {
return 0;
63
// Outputs 8 (5 + 3)
Example
return x + y;
int main() {
cout << z;
return 0;
// Outputs 8 (5 + 3)
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
int z = x;
x = y;
y = z;
int main() {
64
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
return 0;
Function Overloading
With function overloading, multiple functions can have the same name with different
parameters:
Example
int myFunction(int x)
float myFunction(float x)
Consider the following example, which have two functions that add numbers of different type:
Example
return x + y;
return x + y;
int main() {
65
cout << "Int: " << myNum1 << "\n";
return 0;
Instead of defining two functions that should do the same thing, it is better to overload one.
In the example below, we overload the plusFunc function to work for both int and double:
Example
return x + y;
return x + y;
int main() {
return 0;
Note: Multiple functions can have the same name as long as the number and/or type of
parameters are different.
66
What is OOP?
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.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Apple
Fruit Banana
Mango
Watermelon
Class Object
Another example:
Volvo
Car Audi
Toyota
Honda
Class Object
So, a class is a template for objects, and an object is an instance of a class. 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 section.
67
Classes and Objects
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
Example
};
Example explained
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 specifier
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.
68
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
};
int main() {
myObj.myNum = 15;
return 0;
69
Multiple Objects
Example
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";
70
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
Class Methods
Methods are functions that belong to the class. There are two ways to define functions that
belong to a 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
};
int main() {
return 0;
71
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 specifying the name of the class, followed the scope
resolution :: operator, followed by the name of the function:
Outside Example
};
void MyClass::myMethod() {
int main() {
return 0;
Parameters
Example
#include <iostream>
class Car {
72
public:
};
return maxSpeed;
int main() {
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
MyClass() { // Constructor
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
73
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 has brand, model and year attributes, and a constructor with different
parameters. Inside the constructor we set the attributes equal to the constructor parameters
(brand=x, etc). When we call the constructor (by creating an object of the class), we pass
parameters to the constructor, which will set the value of the corresponding attributes to the
same:
Example
brand = x;
model = y;
year = z;
};
int main() {
// Create Car objects and call the constructor with different values
74
Car carObj1("BMW", "X5", 1999);
// 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
};
brand = x;
model = y;
year = z;
75
int main() {
// Create Car objects and call the constructor with different values
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
Access Specifier
By now, you are quite familiar with the public keyword that appears in all of our class examples:
Example
};
The public keyword is an access specifier. Access specifier defines 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?
76
In the following example, we demonstrate the differences between public and private members:
Example
class MyClass {
};
int main() {
MyClass myObj;
return 0;
error: y is private
Note: It is possible to access private members of a class using a public method inside the same
class. See the next chapter (Encapsulation) on how to do this.
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
section.
Note: By default, all members of a class are private if you don't specify an access specifier:
77
Example
class MyClass {
};
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>
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
78
// Getter
int getSalary() {
return salary;
};
int main() {
Employee myObj;
myObj.setSalary(50000);
return 0;
Example explained
The salary attribute is private, which have restricted access. The public setSalary() method takes
a parameter (s) and assigns it to the salary attribute (salary = s). The public getSalary() method
returns the value of the private salary attribute. Inside main(), we create an object of the
Employee class. Now we can use the setSalary() method to set the value of the private attribute
to 50000. Then we call the getSalary() method on the object to return the value.
Why Encapsulation?
It is considered good practice to declare your class attributes as private (as often as you can).
Encapsulation ensures better control of your data, because you (or others) can change one part of
the code without affecting other parts
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
79
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle
class (parent):
Example
// Base class
class Vehicle {
public:
void honk() {
};
// Derived class
public:
};
int main() {
Car myCar;
myCar.honk();
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.
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
class MyClass {
public:
void myFunction() {
};
};
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
81
Multiple Inheritance
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() {
};
class MyOtherClass {
public:
void myOtherFunction() {
};
// Derived class
};
int main() {
MyChildClass myObj;
myObj.myFunction();
82
myObj.myOtherFunction();
return 0;
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
// Base class
class Employee {
int salary;
};
// Derived class
public:
int bonus;
void setSalary(int s) {
salary = s;
int getSalary() {
return salary;
};
83
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
return 0;
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.).
Example
// Base class
class Animal {
public:
void animalSound() {
};
// Derived class
84
public:
void animalSound() {
};
// Derived class
public:
void animalSound() {
};
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() {
};
// Derived class
85
public:
void animalSound() {
};
// Derived class
public:
void animalSound() {
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
It is useful for code reusability: reuse attributes and methods of an existing class when you create
a new class.
86
C++ Files
The fstream library allows us to work with files. To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:
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
To create a file, use either the ofstream or fstream class, and specify the name of the file.
Example
#include <iostream>
#include <fstream>
int main() {
ofstream MyFile("filename.txt");
87
MyFile << "Files can be tricky, but it is fun enough!";
MyFile.close();
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
string myText;
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
MyReadFile.close();
88
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).
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors while it is being
executed. The throw keyword throws an exception when a problem is detected, which lets us
create a custom error. The catch statement allows you to define a block of code to be executed, if
an error occurs in the try block.
Example
try {
catch () {
Example
try {
89
} else {
throw (age);
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
You can also use the throw keyword to output a reference number, like a custom error
number/code for organizing purposes:
Example
try {
} else {
throw 505;
90
}
If you do not know the throw type used in the try block, you can use the "three dots" syntax (...)
inside the catch block, which will handle any type of exception:
Example
try {
} else {
throw 505;
catch (...) {
91
REFERENCES/FURTHER READING
Hubbard, J.R. (2000) Programming with C++, Tata McGraw-Hill, New Delhi, India (Second
Edition)
Paul and Harvey Deitel (2013) C++ How to Program, Pearson Horizon Editions, Eight Edition
https://www.w3schools.com/cpp/
https://www.educba.com/best-c-plus-plus-compiler/
92