DIT 0301/HCT 0201: Object Oriented Programming
DIT 0301/HCT 0201: Object Oriented Programming
0201:
OBJECT
ORIENTED
PROGRAMMING
DIT 0301/HCT 0201: OOP 1
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
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.
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.
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.
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.
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.
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.
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;
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:
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;
For example:
int a (0);
// 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.
Example:
#include <iostream>
using namespace std;
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'
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
\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
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
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
Page | 13
DIT 0301/HCT 0201: OOP 14
> 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.
&& Called Logical AND operator. If both the operands are (A && B)
true, then condition becomes true. is false.
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.
++a Pre-increment
a++ Post-increment
--a Pre-decremen
t
a-- Post-decrement
cout<<”Enter n”;
cin>>n
Page | 15
DIT 0301/HCT 0201: OOP 16
• The if Statement
• if else Statement
Page | 16
DIT 0301/HCT 0201: OOP 17
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";
}
Example:
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Page | 17
DIT 0301/HCT 0201: OOP 18
Syntax;
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Page | 18
DIT 0301/HCT 0201: OOP 19
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.
♦ 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 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++;
}
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.
For statement is divided into three expressions each is separated by semi colon;
Page | 21
DIT 0301/HCT 0201: OOP 22
Example:
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Page | 22
DIT 0301/HCT 0201: OOP 23
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"};
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;
}
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;
}
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;
}
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
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;
Page | 28
DIT 0301/HCT 0201: OOP 29
carObj2.model = "Mustang";
carObj2.year = 1969;
Class Methods
Methods are functions that belongs to the class. There are two ways to define functions that
belongs to a class:
Page | 29
DIT 0301/HCT 0201: OOP 30
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 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
Access Specifiers
Access specifiers define how the members (attributes and methods) of a class can be accessed.
In C++, there are three access specifiers:
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