0% found this document useful (0 votes)
73 views35 pages

DIT 0301/HCT 0201: Object Oriented Programming

The document discusses the basic concepts of object-oriented programming including objects, classes, encapsulation, inheritance, polymorphism, and abstraction. It also provides examples of different types of inheritance and polymorphism. The document is an introduction to object-oriented programming concepts.

Uploaded by

ISAAC
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views35 pages

DIT 0301/HCT 0201: Object Oriented Programming

The document discusses the basic concepts of object-oriented programming including objects, classes, encapsulation, inheritance, polymorphism, and abstraction. It also provides examples of different types of inheritance and polymorphism. The document is an introduction to object-oriented programming concepts.

Uploaded by

ISAAC
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

9 DIT 0301/HCT

0201:
OBJECT
ORIENTED
PROGRAMMING
DIT 0301/HCT 0201: OOP 1

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING


Object-oriented programming (OOP) is a programming paradigm based upon objects (having
both data and methods) that aims to incorporate the advantages of modularity and reusability.
Objects, which are usually instances of classes, are used to interact with one another to design
applications and computer programs. OOP allows decomposition of a problem into a number
of entities called objects and then builds data and function around these objects.
The important features of object–oriented programming are:
i. Bottom–up approach in program design
ii. Programs organized around objects, grouped in classes
iii. Focus on data with methods to operate upon object’s data
iv. Interaction between objects through functions
v. Reusability of design through creation of new classes by adding features to existing
classes
Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi,
C#, Perl, Python, Ruby, and PHP.

Basic Concepts and Terminologies of Object–Oriented Systems


1. Object
An object is a real-world element in an object–oriented environment that may have a physical
like a customer, a car, etc. or an intangible conceptual existence like a project, a process, etc.
An object is an instance of a class. Each object has three properties.

Properties of an object
i. Identity: it is that property of an object, which distinguishes it from all others in the
system. It is the name held within an object. For example; student, lecturer, book etc. ii.
State: it determines the characteristic properties of an object as well as the values of the
properties that the object holds. For example; for a student, name, Registration number,
gender, age, course etc.
iii. Behavior: it represents externally visible activities performed by an object in terms of
changes in its state. For example; a student can attend classes, sit for exams, pay fees
etc.

2. Class

A class represents a collection of objects having same characteristic/properties that exhibit


common behavior. It gives the blueprint or description of the objects that can be created from
it. Creation of an object as a member of a class is called instantiation. Thus, object is an
instance of a class. It is a template from which objects are created.

3. Encapsulation
Encapsulation is the process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from outside. It permits
the elements of the class to be accessed from outside only through the interface provided by
the class.

4. Data Hiding

Page | 1
DIT 0301/HCT 0201: OOP 2

Typically, a class is designed such that its data (attributes) can be accessed only by its class
methods and insulated from direct outside access. This process of insulating an object’s data is
called data hiding or information hiding.

5. Message Passing
Any application requires a number of objects interacting in a harmonious manner. Objects in a
system may communicate with each other using message passing. Suppose a system has two
objects: obj1 and obj2. The object obj1 sends a message to object obj2, if obj1 wants obj2 to
execute one of its methods.

The features of message passing are:


♦ Message passing between two objects is generally unidirectional.
♦ Message passing enables all interactions between objects.
♦ Message passing essentially involves invoking class methods.
♦ Objects in different processes can be involved in message passing.

6. Inheritance
Inheritance is the mechanism in which a sub class acquires some or all its characteristics from
the base class. Inheritance that permits new classes to be created out of existing classes by
extending and refining its capabilities. The existing classes are called the base classes/parent
classes/super-classes, and the new classes are called the derived classes/child
classes/subclasses. The subclass can inherit or derive the attributes and methods of the super
class(es) provided that the super-class allows so. Besides, the subclass may add its own
attributes and methods and may modify any of the super-class methods. Inheritance defines an
“is – a” relationship.

Example
From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow,
etc. Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In
addition, each has its own particular characteristics. It can be said that a cow “is – a”
mammal.
Types of Inheritance
i. Single inheritance: it is a type of inheritance in which a subclass derives/acquires it
characteristics from a single super-class.
ii. Multiple inheritance: it is a type of inheritance in which a subclass derives/acquires it
characteristics from more than one super-classes.
iii. Multilevel inheritance: it is a type of inheritance in which a subclass derives/acquires it
characteristics from a super-class which in turn is derived from another class and so
on.
iv. Hierarchical inheritance: A class has a number of subclasses each of which may have
subsequent subclasses, continuing for a number of levels, so as to form a tree structure. v.
Hybrid Inheritance: A combination of multiple and multilevel inheritance so as to form a
lattice structure.

The following figure depicts the examples of different types of inheritance.

Page | 2
DIT 0301/HCT 0201: OOP 3
7. Polymorphism
Polymorphism is originally a Greek word that means the ability to take multiple forms. It is a
mechanism in which different objects react differently to the same message. Example
Let us consider two classes, Circle and Square, each with a method findArea(). Though the
name and purpose of the methods in the classes are same, the internal implementation, i.e., the
procedure of calculating area is different for each class. When an object of class Circle
invokes its findArea() method, the operation finds the area of the circle without any conflict
with the findArea() method of the Square class.

Page | 3
DIT 0301/HCT 0201: OOP 4
The figure
illustrates that a single function name can be used to handle different number and different
types of argument. Using a single function name to perform different type of task is known as
function overloading.

Types of Polymorphism
i. Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same
name, if the parameters of methods are different in number, sequence and data types of
parameters.
ii. Runtime Polymorphism (or Dynamic polymorphism)
Dynamic polymorphism is a process in which a call to an overridden method is
resolved at runtime. Method Overriding is what allows a subclass to replace methods
on the superclass with their own behaviour.

8. Data abstraction
It refers to the act of representing essential features without including the background
details or explanation. Classes use the concept of abstraction and are defined as a list of
abstract attributes such as size, wait, and cost, and function operate on these attributes.
9. Methods
A method is basically a behaviour. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed. The
attributes are some time called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
Page | 4
DIT 0301/HCT 0201: OOP 5

C++
C++ Introduction
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at
AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. C+ + is a
superset of C. The most important facilities that C++ adds on to C are classes, inheritance,
function overloading and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby making
C++ a truly object-oriented language.
The C++ language consists of two basic elements:
i. Semantics: This is a vocabulary of commands that humans can understand and that can
be converted into machine language, fairly easily.
ii. Syntax: This is a language structure (or grammar) that allows humans to combine these
C++ commands into a program that actually does something.
A C++ program is a text file containing a sequence of C++ commands put together according
to the laws of C++ grammar. This text file is known as the source file. A C++ source file
carries the extension .CPP
The point of programming in C++ is to write a sequence of commands that can be converted
into a machine-language program that actually does what we want done. The resulting
machine-executable files carry the extension .EXE. The act of creating an executable program
from a C++ program is called compiling or building.

C++ Getting Started


To start using C++, you need two things:
i. A text editor to write C++ code.
ii. A compiler to translate the C++ code into a language that the computer will understand.
There are many text editors and compilers to choose from.

C++ PROGRAM STRUCTURE:


Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;

// main() is where program execution begins.

int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Page | 5
DIT 0301/HCT 0201: OOP 6

1. #include <iostream>
This line is a preprocessing directive. All preprocessing directives within C++ source code
begin with a # symbol. This is a header file library that lets us work with input and output
objects, such as cout.

2. using namespace std;


This means that we can use names for objects and variables from the standard library.

3. int main() {
This specifies the real beginning of our program. Here we are declaring a function named
main. All C++ programs must contain this function to be executable.
The opening curly brace at the end of the line marks the beginning of the body of a
function. The body of a function contains the statements the function is to execute.

4. cout << "This is a simple C++ program!\n";


It is an object used together with the insertion operator (<<) to output/print text. This
statement directs the executing program to print the message.
A statement is the fundamental unit of execution in a C++ program and should end with a
semicolon (;). In C++, the semicolon is a statement terminator.
5. return 0;
The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C++ console program.
6. }
The closing curly brace marks the end of the body of a function. Both the open curly brace
and close curly brace are required for every function definition.

COMMENTS
Comments are parts of the source code disregarded by the compiler. They allow the
programmer to insert notes or descriptions embedded within the source code. 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. A comment may start anywhere in the line, and
whatever follows until the end of the line is ignored.
We have two main types of comments.

1. Single line comment


It discards everything from where the pair of slash signs (//) is found up to the end of that
same line. It is represented using the double slash symbol. Examples:
// This is a comment
cout << "Hello World!";

Page | 6
DIT 0301/HCT 0201: OOP 7

Or
cout << "Hello World!"; // This is a comment

2. Multiline comments
Also known as block comment, discards everything between the /* characters and the first
appearance of the */ characters, with the possibility of including more than one line.
Represented using the /*,*/ symbols. Example:
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

VARIABLES
Variables are containers for storing data values. A variable definition tells the compiler where
and how much storage to create for the variable.

C++ Identifiers
All C++ variables must be identified with unique names. These unique names are called
identifiers. Each variable needs an identifier that distinguishes it from the others. We can call
the variables any names we want to invent as long as they are valid identifiers. It is
recommended to use descriptive names in order to create understandable and maintainable
code.
Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

Rules of Naming Variables


The general rules for constructing names for variables (unique identifiers) are:
i. Names can contain letters, digits and underscores. first Name9
ii. Names must begin with a letter or an underscore (_) but not a digit. iii. Names are case
sensitive. Thus, for example, the RESULT variable is not the same as the result variable or
the Result variable. These are three different variable identifiers. iv. Names cannot contain
whitespaces or special characters like !, #, %, etc. v. Reserved words (like C++ keywords,
such as int) cannot be used as names

DECLARATION OF VARIABLES

Page | 7
DIT 0301/HCT 0201: OOP 8

In order to use a variable in C++, we must first declare it specifying which data type we want
it to be. The syntax to declare a new variable is to write the specifier of the desired data type
(like int, bool, float...) followed by a valid variable identifier. For example:
int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int with
the identifier a. The second one declares a variable of type float with the identifier
mynumber. Once declared, the variables a and mynumber can be used within the rest of their
scope in the program.
If you are going to declare more than one variable of the same type, you can declare all of
them in a single statement by separating their identifiers with commas. For example:
int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same
meaning as:
int a;
int b;
int c;

Example:

// operating with variables


#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}

Page | 8
DIT 0301/HCT 0201: OOP 9

INITIALIZATION OF VARIABLES
When declaring a regular local variable, its value is by default undetermined. But you may
want a variable to store a concrete value at the same moment that it is declared. In order to do
that, you can initialize the variable. There are two ways to do this in C++:
i. c-like
The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the
moment in which it is declared, we could write:
int a = 0;

ii. Constructor initialization


The other way to initialize variables, known as constructor initialization, is done by
enclosing the initial value between parentheses (()):
type identifier (initial_value) ;

For example:
int a (0);

Both ways of initializing variables are valid and equivalent in C++.

// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value
undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}

Page | 9
DIT 0301/HCT 0201: OOP 10

SCOPE OF VARIABLES
All the variables that we intend to use in a program must have been declared with its type
specifier in an earlier point in the code.
A variable can be either of two scopes;
i. Global variable
A global variable is a variable declared in the main body of the source code, outside all
functions. Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.

ii. Local variable


A local variable is one declared within the body of a function or a block. The scope of local
variables is limited to the block enclosed in braces ({}) where they are declared. For example,
if they are declared at the beginning of the body of a function (like in function main) their
scope is between its declaration point and the end of that function. In the example above, this
means that if another function existed in addition to main, the local variables declared in main
could not be accessed from the other function and vice versa.

Example:
#include <iostream>
using namespace std;

// Global variable declaration:


int g;

int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

Page | 10
DIT 0301/HCT 0201: OOP 11

DATA TYPES
When programming, we store the variables in our computer's memory, but the computer has
to know what kind of data we want to store in them. This is because no all data types occupy
the same amount of memory. The data type specifies the size and type of information the
variable will store.
The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte can store a relatively small amount of data: one
single character or a small integer (generally an integer between 0 and 255.
Basic fundamental data types in C++ include;
i. int: size is 4 bytes. Stores whole numbers, without decimals.
ii. float: size is 4 bytes. Stores fractional numbers, containing one or more decimals.
Sufficient for storing 7 decimal digits
iii. double: size is 8 bytes. Stores fractional numbers, containing one or more decimals.
Sufficient for storing 15 decimal digits
iv. boolean: size is 1 byte. Stores true or false values
v. char: size is 1 byte. Stores a single character/letter/number, or ASCII values vi.
wchar_t Wide character.
vii. void: Represents the absence of type.
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

C++ CONSTANTS/LITERALS
Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.
When you do not want to override existing variable values, use the const keyword. This will
declare the variable as "constant", which means unchangeable and read-only. Their values
cannot be modified after their definition. Always declare the variable as constant when you
have values that are unlikely to change.
Example:
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

Characters with Special Meaning

Page | 11
DIT 0301/HCT 0201: OOP 12

There are certain characters in C++ when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a
list of some of such escape sequence codes –
Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab
\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

INTRODUCTION TO STRINGS
Variables that can store non-numerical values that are longer than one single character are
known as strings. The string type is used to store a sequence of characters (text). String
values must be surrounded by double quotes.
The C++ language library provides support for strings through the standard string class. In
order to declare and use objects (variables) of this type we need to include an additional
header file in our source code: <string> and have access to the std namespace.

// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Page | 12
DIT 0301/HCT 0201: OOP 13

C++ USER INPUT


We 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
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

Quiz: Write a simple program that asks the user to input two numbers. Then calculates and
outputs the sum of the two numbers.

C++ OPERATORS
Operators are used to perform operations on variables and values. An operator is a symbol
that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich
in built-in operators and provide the following types of operators −
i. Arithmetic Operators
ii. Relational Operators
iii. Logical Operators
iv. Assignment Operators
v. Increment and Decrement Operators

i. Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give


200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give


integer division 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Page | 13
DIT 0301/HCT 0201: OOP 14

ii. Relational Operators


There are following relational operators supported by C++ language.
Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example

== Checks if the values of two operands are equal or not, if (A == B) is


yes then condition becomes true. not true.

!= Checks if the values of two operands are equal or not, (A != B) is


if values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value (A > B) is
of right operand, if yes then condition becomes true. not true.

< Checks if the value of left operand is less than the value (A < B) is
of right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal (A >= B) is
to the value of right operand, if yes then condition not true.
becomes true.

iii. Logical Operators ~#\¦¦``¬¬///


There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example

&& Called Logical AND operator. If both the operands are (A && B)
true, then condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands (A || B) is true.


is true, then condition becomes true.

! Called Logical NOT Operator. Reverses the result, !(A && B)


returns false if the result is true is true.

iv. Assignment Operators


There are following assignment operators supported by C++ language –
Operator Description Example

= Simple assignment operator, Assigns values C = A + B will


from right side operands to left side operand. assign value of A +
B into C

+= Add AND assignment operator, It adds right C += A is


operand to the left operand and assign the result to equivalent to C =
left operand. C+A

Page | 14
DIT 0301/HCT 0201: OOP 15
-= Subtract AND assignment operator, It subtracts C -= A is equivalent
right operand from the left operand and assign the to C = C - A
result to left operand.

*= Multiply AND assignment operator, It C *= A is equivalent


multiplies right operand with the left operand to C = C * A
and assign the result to left operand.

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the to C = C / A
result to left operand.
%= Modulus AND assignment operator, It takes C %= A is
modulus using two operands and assign the result equivalent to C =
to left operand. C%A

<<= Left shift AND assignment operator. C <<= 2 is same as


C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as


C = C >> 2

v. Increment and Decrement Operators


Increment (++) and Decrement (--) Operators. The operator ++ adds one to its operand
whereas the operator - - subtracts one from its operand. These operators are unary operators
and take the following form:
Description

++a Pre-increment

a++ Post-increment

--a Pre-decremen
t

a-- Post-decrement

vi. Insertion and Extraction Operators


Insertion (<<) and Extraction (>>) operators: the operators are use with output and input
objects Example:

cout<<”Enter n”;
cin>>n

Page | 15
DIT 0301/HCT 0201: OOP 16

OPERATORS PRECEDENCE IN C++


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
C++ CONTROL STRUCTURES
Statements are usually executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation, when you need to execute
a block of code several number of times. Programming languages provide various control
structures that allow for more complicated execution paths.
The flow of execution of statements in a program is called a control. Control statement is a
statement, which controls flow of execution of the program. Control statements are classified
into following categories.
i. Sequential control statements
ii. Conditional control statements
iii. Unconditional control statements

1. Sequential control statements


Ensures that the instructions (or statements) are executed in the same order in which they
appear in the program. i.e. By default system executes the statements in the program in
sequential order.
2. Conditional control statements (C++ Conditionals)
Statements that are executed when a condition is true. These statements are divided into three
categories. They are;
a. Decision making statements
b. Switch case control statement
c. Loop control statements or repetitions

a. DECISION MAKING STATEMENTS


These statements are used to control the flow of execution of a program by making a
decision depending on a condition; hence, they are named as decision-making
statements. Decision-making statements are of several types;

• The if Statement
• if else Statement
Page | 16
DIT 0301/HCT 0201: OOP 17

• The else if Statement

i. The if Statement
If the test expression/condition is true then if statement executes statements that
immediately follow if.
Syntax:
If (test expression)
{
List of statements;
}

Example:
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

ii. if else statement


If test expression/condition is true, block of statements following if are executed
and if test expression is false then statements in else block are executed.
Syntax;
if (test expression)
{
statement block1;
}
else
{
statement block2;
}

Example:
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

Page | 17
DIT 0301/HCT 0201: OOP 18

iii. The else if Statement


It is also possible to nest one if statement inside another. When a series of
decisions are to be made. If –else statement placed inside another if else statement
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.";
}

b. SWITCH CASE CONTROL STATEMENT


THE SWITCH STATEMENT
Suppose we have more than one valid choices to choose from then we can use
switch statement in place of if 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
}

This is how it works:

Page | 18
DIT 0301/HCT 0201: OOP 19

▪ 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.

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";

Page | 19
DIT 0301/HCT 0201: OOP 20

break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}

Note: When C++ reaches a break keyword, it breaks out of the switch block. The default
keyword must be used as the last statement in the switch, and it does not need a break.

c. LOOP CONTROL STATEMENTS OR REPETITIONS (C++ LOOPS)


A block or group of statements executed repeatedly until some condition is satisfied is called
Loop. The group of statements enclosed within curly brace is called block or compound
statement.
We have two types of looping structures.

♦ One in which condition is tested before entering the statement block called entry
control.
♦ The other in which condition is checked at exit called exit-controlled loop.
Loop statements can be divided into three categories as given below

i. while loop statement


ii. do while loop statement
iii. for loop statement

i. WHILE STATEMENT
The while loop loops through a block of code as long as a specified condition is true. It is an
entry controlled loop. The condition is evaluated and if it is true then body of loop is executed.
After execution of body the condition is once again evaluated and if is true body is executed
once again. This goes on until test condition becomes false.
Syntax:
while (condition) {
// code block to be executed
}

Page | 20
DIT 0301/HCT 0201: OOP 21
Example:
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

ii. DO WHILE STATEMENT


This loop will execute the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true. The while loop does not allow body to be
executed if test condition is false. The do while is an exit controlled loop and its body is
executed at least once.
Syntax:
do {
// code block to be executed
}
while (condition);
Example:
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

Note: if test condition is false before the loop is being executed then While loop executes zero
number of times where as dowhile executes one time.

iii. FOR LOOP


It is also an entry control loop that provides a more concise structure. Used when you know
exactly how many times you want to loop through a block of code.
Syntax:
For (initialization; test expression; increment/decrement)
{
statements;
}

For statement is divided into three expressions each is separated by semi colon;
Page | 21
DIT 0301/HCT 0201: OOP 22

♦ Initialization expression is used to initialize variables.


♦ Test expression is responsible of continuing the loop. If it is true, then the program
control flow goes inside the loop and executes the block of statements associated with
it. If test expression is false loop terminates
♦ Increment/decrement expression consists of increment or decrement operator.
This process continues until test condition satisfies.

Example:
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

3. Unconditional Control Statements


These are statements that transfers control from on part of the program to another part
unconditionally. Different unconditional statements are
i. goto
ii. break
iii. continue

i. The goto Keyword


goto statement is used for unconditional branching or transfer of the program execution to the
labelled statement.
ii. The break Keyword
When C++ reaches a break keyword, it breaks out of the switch block. This will stop the
execution of more code and case testing inside the block. When a match is found, and the job
is done, it's time for a break. There is no need for more testing. 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.
When a break statement is encountered within a loop, the loop is immediately exited and the
program continues with the statements immediately following loop.

Page | 22
DIT 0301/HCT 0201: OOP 23

iii. The Continue Keyword


It is used to continue the iteration of the loop statement by skipping the statements after
continue statement. It causes the control to go directly to the test condition and then to
continue the loop.
Example;
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}

C++ ARRAYS
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store:
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:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of three integers, you could write:


int myNum[3] = {10, 20, 30};

Access the Elements of an Array


You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
Change an Array Element
To change the value of a specific element, refer to the index number:
cars[0] = "Opel";
Page | 23
DIT 0301/HCT 0201: OOP 24

Loop Through an Array


You can loop through the array elements with the for loop.
The following example outputs all elements in the cars array:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}

The following example outputs the index of each element together with its value:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}

C++ FUNCTIONS
A function is a block of code that performs a task. It 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.
Every C++ program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function (code to be executed).
void myFunction() { // declaration
// the body of the function (definition)
}

Defining a Function
The general form of a C++ function definition is as follows –
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −
i. Return Type: A function may return a value. The return_type is the data type of the
value the function returns.

Page | 24
DIT 0301/HCT 0201: OOP 25

ii. Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
iii. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
iv. Function Body: The function body contains a collection of statements that define what
the function does.

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when its
function ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value. For example –
// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

A function can be called multiple times:


void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

Types of function
We have two types of function in C++:

Page | 25
DIT 0301/HCT 0201: OOP 26

i. Built-in functions are also known as library functions. We need not to declare and define
these functions as they are already written in the C++ libraries such as iostream,
cmath etc. We can directly call them when we need.
ii. User-defined functions: The functions that we declare and write in our programs are
user-defined functions.

Function Overloading
Allows multiple functions to have the same name with different parameters. Multiple
functions can have the same name as long as the number and/or type of parameters are
different.
Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

In the example below, we overload the plusFunc function to work for both int and double:
int plusFunc(int x, int y) {
return x + y;
}

double plusFunc(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Function Overriding
It is a feature that allows us to have a same function in child class which is already present in
the parent class. A child class inherits the data members and member functions of parent class,
but when you want to override a functionality in the child class then you can use function
overriding. It is like creating a new version of an old function, in the child class.
Example:
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}

Page | 26
DIT 0301/HCT 0201: OOP 27

};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}

C++ CLASSES AND OBJECTS


A class is a template for creating objects, and an object is an instance of a class. Example: a
Class Car can have Nissan, Audi, Volvo as its objects or a Class fruit can have Mango,
Pineapple, Apple as it’s objects. When the individual objects are created, they inherit all the
variables and functions from the class.

Create a Class
To create a class, use the class keyword.
Example:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Example explained
i. The class keyword is used to create a class called MyClass.
ii. The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class.
iii. 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.
iv. At last, end the class definition with a semicolon;.

Create an Object

Page | 27
DIT 0301/HCT 0201: OOP 28

In C++, an object is created from a class. 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:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

Multiple Objects
You can create multiple objects of one class.
Example:
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};

int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";

Page | 28
DIT 0301/HCT 0201: OOP 29

carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}

Classes and Objects in Detail


Interesting concepts related to C++ Classes and Objects
i. Class Member Functions: A member function of a class is a function that has its
definition or its prototype within the class definition like any other variable. ii. Class Access
Modifiers: A class member can be defined as public, private or protected. By default
members would be assumed as private.
iii. Constructor & Destructor: A class constructor is a special function in a class that is
called when a new object of the class is created. A destructor is also a special function,
which is called when created object is deleted.
iv. Copy Constructor: The copy constructor is a constructor which creates an object by
initializing it with an object of the same class, which has been created previously. v. Friend
Functions: A friend function is permitted full access to private and protected members of a
class. It is declared as friend. Example: friend class ABC;
vi. Inline Functions: With an inline function, the compiler tries to expand the code in the
body of the function in place of a call to the function.
vii. this Pointer: Every object has a special pointer this which points to the object itself. viii.
Pointer to C++ Classes: A pointer to a class is done exactly the same way a pointer to a
structure is. In fact a class is really just a structure with functions in it.
ix. Static Members of a Class: Both data members and function members of a class can be
declared as static.

Class Methods
Methods are functions that belongs to the class. There are two ways to define functions that
belongs to a class:

• Inside class definition


• Outside class definition
Example:
We define a function inside the class, and we name it "myMethod". You access methods just
like you access attributes; by creating an object of the class and using the dot syntax (.)

Page | 29
DIT 0301/HCT 0201: OOP 30

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

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:
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 return 0;
}

C++ Constructors
A constructor in C++ is a special method that is automatically called when an object of a class
is created. To create a constructor, use the same name as the class, followed by parentheses ().
The constructor has the same name as the class, it is always public, and it does not have any
return value.
Example:
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
Page | 30
DIT 0301/HCT 0201: OOP 31

MyClass myObj; // Create an object of MyClass (this will call the


constructor)
return 0;
}

Access Specifiers
Access specifiers define how the members (attributes and methods) of a class can be accessed.
In C++, there are three access specifiers:

i. Public - members are accessible from outside the class


ii. Private - members cannot be accessed (or viewed) from outside the class iii. Protected -
members cannot be accessed from outside the class, however, they can be accessed in
inherited classes.
By default, all members of a class are private if you don't specify an access specifier.

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:
To access a private attribute, use public "get" and "set" methods:
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();
Page | 31
DIT 0301/HCT 0201: OOP 32

return 0;
}

Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. A class can
be derived from more than one classes, which means it can inherit data and functions from
multiple base classes. We group the "inheritance concept" into two categories:
i. Base class (parent) - the class being inherited from
ii. Derived class (child) - the class that inherits from another class
To inherit from a class, use the : symbol. Inheritance is useful for code reusability: reuse
attributes and methods of an existing class when you create a new class.

In the example below, the Car class (child) inherits the attributes and methods from the
Vehicle class (parent):
// 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;
}

Page | 32

You might also like