Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Object Oriented Programming

Table of Contents

Lesson 1 - Object Oriented Language Fundamentals ............................................................................5


What is C++ ............................................................................................................................................... 5
C++ Program Structure ............................................................................................................................. 5
The iostream.h File ................................................................................................................................... 5
Output Operator ....................................................................................................................................... 5
Comments ................................................................................................................................................. 6
Input Operator .......................................................................................................................................... 6
Return Statement ..................................................................................................................................... 6
Tokens ....................................................................................................................................................... 6
Keywords................................................................................................................................................... 7
Identifiers .................................................................................................................................................. 7
Strings ....................................................................................................................................................... 8
Punctuators ............................................................................................................................................... 8
Operators .................................................................................................................................................. 8
Data Types................................................................................................................................................. 9
Variables | Arrays | Pointers .................................................................................................................. 10
Control Structures ................................................................................................................................... 11
a. Sequence Structure. ........................................................................................................................ 11
b. Selection Structure.......................................................................................................................... 11
c. Repetition Structure........................................................................................................................ 12
Functions in C++ ...................................................................................................................................... 13
Lesson 2 - Principles of Object-Oriented Programming ...................................................................... 14
Introduction to Object Oriented Programming .................................................................................. 14
Class vs Object ................................................................................................................................. 14
Object Oriented Features ................................................................................................................. 15
• Encapsulation ........................................................................................................................... 15
• Abstraction............................................................................................................................... 15
• Inheritances ............................................................................................................................. 15
• Polymorphism .......................................................................................................................... 15
1. Encapsulation ........................................................................................................................... 15

DCSD/DSE/DNE 1
Object Oriented Programming

2. Abstraction............................................................................................................................... 15
3. Inheritance ............................................................................................................................... 15
4. Polymorphism .......................................................................................................................... 15
Lesson 3 - Encapsulation and Abstraction ......................................................................................... 16
Class Definition ....................................................................................................................................... 16
Function Definition ................................................................................................................................. 17
Outside class definition : ...................................................................................................................... 17
Inside class definition : ......................................................................................................................... 18
Object Definition ..................................................................................................................................... 18
Accessing Members ................................................................................................................................ 19
Private Functions .................................................................................................................................... 20
Static Members and Instance members ................................................................................................. 21
Attribute as an Array ............................................................................................................................... 21
Objects as Function Arguments .............................................................................................................. 22
Return objects ......................................................................................................................................... 23
Memory Allocation for Objects............................................................................................................... 25
Lesson 4 - Constructors and Destructors ........................................................................................... 26
Introduction to Constructor .................................................................................................................... 26
Introduction to Destructor...................................................................................................................... 30
Lesson 5 – Inheritance ...................................................................................................................... 32
Introduction ............................................................................................................................................ 32
Benefits of inheritance............................................................................................................................ 32
Protected Label ....................................................................................................................................... 32
Private Inheritance.................................................................................................................................. 33
Protected Inheritance ............................................................................................................................. 34
Inheritance with Constructors ................................................................................................................ 35
Forms of Inheritance ............................................................................................................................... 37
Single Inheritance ................................................................................................................................... 37
Lesson 6 - Polymorphism .................................................................................................................. 40
Introduction ............................................................................................................................................ 40
Virtual Functions ........................................................................................ Error! Bookmark not defined.
Pure Virtual Function ................................................................................. Error! Bookmark not defined.
Lesson 7 - File Operation .................................................................................................................. 45

DCSD/DSE/DNE 2
Object Oriented Programming

Introduction ............................................................................................................................................ 46
Working with single files ......................................................................................................................... 47
Working with multiple files ..................................................................................................................... 50
Working with multiple files simultaneously ........................................................................................... 53
File Modes ............................................................................................................................................... 55
Working with Classes and Files ............................................................................................................... 56
File Pointers ............................................................................................................................................ 58
Manipulation of File Pointers.................................................................................................................. 58
References....................................................................................................................................... 61

List of Figures
Figure 1 ....................................................................................................................................................... 33
Figure 2 ....................................................................................................................................................... 33
Figure 3 ....................................................................................................................................................... 34
Figure 4 - Forms of inheritance ................................................................................................................... 37
Figure 5 - File input and output streams..................................................................................................... 46
Figure 6 - Action of single argument seek function .................................................................................... 59

DCSD/DSE/DNE 3
Object Oriented Programming

List of Tables
Table 1........................................................................................................................................................... 7
Table 2........................................................................................................................................................... 9

DCSD/DSE/DNE 4
Object Oriented Programming

Lesson 1 - Object Oriented Language Fundamentals

What is C++

• C++ is a superset of C.
• The three most important facilities that C++ adds on to C are classes, function overloading,
and operator overloading.
• These features enable us to create abstract data types, inherit properties from existing data
types and support polymorphism.

C++ Program Structure

#include <iostream>
using namespace std;
int main()
{ cout << “C++ is better than C.\n”; //This is a output
return 0;
}

The iostream.h File

• The header file has set predefined library functions.


• #include is the preprocessor directive to use predefined library functions.

Output Operator

• The value which is inserted using insertion operator (<<) is displayed by cout.

DCSD/DSE/DNE 5
Object Oriented Programming

Comments

• The comments are used to explain program codes. These are not compiled or executed.
Format: //
/*
*/

Input Operator

• The value is extracted by cin using extraction operator (>>) and assign to cin.
Format: cin>>variable;

Return Statement

• Returns value 0 to the calling process.

Tokens

Token is the smallest element in a program. Tokens are classified as below.

• Keywords (Reserved words).


• Identifiers.
• Constants.
• Strings (String literals).
• Special Symbols.
• Operators.

DCSD/DSE/DNE 6
Object Oriented Programming

Keywords

• The keywords are reserved words in programming use to perform special functionalities.

asm delete if return try

auto do inline short typedef

break double int signed union

case else long sizeof unsigned

catch enum new static virtual

char extern operator struct void

class float private switch volatile

const for protected template while

continue friend public this

default goto register throw

Table 1

Identifiers

• These are used to name variables, functions, classes, arrays ……etc. Rules for constructing
identifiers:
• Only alphabetic characters, digits and underscores are permitted.
• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A declared keyword cannot be used as a variable name.
• There is virtually no length limitation. However, in many implementations of C++
language, the compilers recognize only the first 32 characters as significant.
• There can be no embedded blanks.

DCSD/DSE/DNE 7
Object Oriented Programming

Strings

• A String constant is a sequence of any number of characters surrounded by double


quotation marks.

E.g.: “This is a string constant.”

Punctuators

• Punctuators in C++ are used to delimit various syntactical units.


• The punctuators (also known as separators) in C++ include the following symbols:
[] () {} , ; : … * #

Operators

• Operators are used to operate data.


• Some examples of operators are:
( ) ++ -- * / % + - << >> < <= > >= ==
!= = += -= *= /= %=

DCSD/DSE/DNE 8
Object Oriented Programming

Data Types

Data type is used to indicate type and size of data which can be stored in a variable. The following
table shows built in data types of C++.

Type Bytes Range

char 1 -128 to 127

unsigned char 1 0 to 255

signed char 1 -128 to 127

int 2 -32768 to 32767

unsigned int 2 0 to 65535

signed int 2 -32768 to 32767

short int 2 -32768 to 32767

unsigned short int 2 0 to 65535

signed short int 2 -32768 to 32767

long int 4 -2147483648 to 2147483647

signed long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Table 2

DCSD/DSE/DNE 9
Object Oriented Programming

Variables | Arrays | Pointers

Variable is a name given to single memory location.it is named applying rules which are used
identifiers. variable is declared using necessary data type to allocate space in the memory.

Format : data_type variable_name;

Example : int number;

Array is set of continues memory locations to hold multiple values. It is a derived data type. Once
we declared an array, all the slots of the array have same type of data and all the slots are equal
size. At the time of declaring an array, size is given to indicate number of slots. Each slot of the
array is accessed by index.

Format : data_type array_name[size];

Example : int number [3];

number [0] =20;

number [1] =50;

Pointer is a variable which is used to hold address of a variable. Address of a variable can be
taken applying operator & with the variable name.

Format : data_type pointer_name;

Example : int *t;

int x;
t=&x;

cout<<t; //Address of x is displayed

cout<<*t; //Value of x is displayed

DCSD/DSE/DNE 10
Object Oriented Programming

Control Structures

a. Sequence Structure.

In sequence structure, instructions written are executed one after the other from
begging to end.

b. Selection Structure.

In selection structure, instructions are executed based on the condition(s) specified.


There are several techniques used to make selections as mentioned below.

if
Format 1 : if (condition_1)
{
}
Format 2 : if (condition_2)
{
}
else
{
}
Format 3 : if (condition_1)
{
}
Else if (condition_2)
{
}
else
{
}

DCSD/DSE/DNE 11
Object Oriented Programming

Format 4 : if (condition_1)
{ if (condition_2)
{
}
}

switch
Format 1 : switch(variable)
{
case value:
case value:
default:

conditional
Format 1 : (condition) ? value_1: value_2;

c. Repetition Structure.

In repetition structure, instructions are repeated based on the condition specified.

while

Format : counter_start
while(counter_condition)
{ instructions to repeat
condition_increment
}

DCSD/DSE/DNE 12
Object Oriented Programming

for

Format :
for (counter_start; counter_condition; condition_increment)
{ instructions to repeat
}
do while

Format : counter_start
do
{ instructions to repeat
condition_increment;
}
While(counter_condition);

Functions in C++

A function is a bock which is used to write set of instructions to be executed.


Format : function_type name_of_the_function(parameters)
{ Statements;
return value;
}
The type of the function is decided by type of value returned by the function. Name of the function
is an identifier. Parameters are used to accept values from outside.

Example : int getAge (int age)


{ Statements;
return age;
}
getAge(15);

DCSD/DSE/DNE 13
Object Oriented Programming

Lesson 2 - Principles of Object-Oriented Programming

Introduction to Object Oriented Programming

Object oriented programming is used to represent real world entity(s) in a program. The real-world
entities are books, students, trees, tables, fans…. etc. The real-world entities are called objects in
programming context.

Class vs Object

Class is a template or blue print which is used to create objects in programming. The class has
attributes and functions.

Example : Class: Student


Attributes : age
weight
functions : walk ()
eat ()

Object represents real world entity and an object(s) is created by a class. The student Amal and
Saman are objects which created by class Student. Values for the attributes decided by object(s).

Example : Object: Amal


Attributes : age = 20
weight = 6.5

Functions : walk ()
eat ()
Example : Object: Saman
Attributes : age = 18
weight = 5.8

Functions : walk ()
eat ()

DCSD/DSE/DNE 14
Object Oriented Programming

Object Oriented Features

The following are main object-oriented features.

• Encapsulation

• Abstraction

• Inheritances

• Polymorphism

1. Encapsulation

Wrapping Attributes and Functions together called Encapsulation. The class is the basic
unit used to implement encapsulation. Attributes are hidden by private label and those are
accessed through methods under public label.

2. Abstraction

Hiding implementation details of a function is called abstraction. For an example when we


send an email, we type email address and message of the email and press compose button
to send the email. But we have no idea how compose button functionality is working as it
hides implementation from the user.

3. Inheritance

Inheritance provides an opportunity to re-use attributes and functions of a class(s) to


another class. There are several types of inheritance available. More details will be
discussed.

4. Polymorphism

Polymorphism is used to show many forms/actions by one name. There are two types of
polymorphism. More details will be discussed.

DCSD/DSE/DNE 15
Object Oriented Programming

Lesson 3 - Encapsulation and Abstraction

Class Definition

The class is a template (Structure) for creating objects. The class consists of attributes and
functions. These are called class members. The attribute is a characteristic and function is
a behavior. The attribute can be represented as a variable or an array in a class.

Format:

class name_of_the_class
{ private:
Attribute(s);
Functions(s);
public:
Attribute(s);
Functions(s);
};

Example:

class Student
{ private:
int age;

public:
void setAge(int);

};

In this example class Student is a template which can be used to represent students in the
real world. The class student consists of attribute age and function setAge().

DCSD/DSE/DNE 16
Object Oriented Programming

Access Labels
Members of the class can be kept under private or public label.
Private :
Members under private are not allowed to use by non-members(outsiders) of the
class. For an example attribute age is kept under private above. So, it cannot be
used by outsiders like main function or any other class. If you don’t a label, by
default private.
Public :
Members under public are allowed to use by non-members(outsiders) of the class
and members of the class. For an example functions setAge() is kept under public
above. So, it can be accessed by non-members of the class like main function or
any other class.

Function Definition

A function can be defined inside the class or outside of the class. The function definition
includes set of instructions to be executed when it is called.

Outside class definition :

Member function can be defined outsider of the class.


Format :
return_type name_of_the_class :: name_of_the_function()
{
}
Example :
void Student:: setAge(int age)
{ this->age=age;
}

DCSD/DSE/DNE 17
Object Oriented Programming

Inside class definition :

Member function can be defined inside the class.


Format :
return_type name_of_the_function ()
{
}
Example:
void setAge(int age)
{
}

Object Definition

The object represents real world entity and it is created by the class in programming. The
object also called instance of the class or copy of the class. For an example nimal, kamal
and sunil are instances of student. Once an object created members of the class received by
the object. Objects nimal, kamal and sunil receive members age and setAge() of the class.
All the objects of class Student have same attributes and functions of class Student.

Format : name_of_the_class name_of_the_object;


Example 1 : Student nimal; Student kamal; Student sunil;
Example 2 : Student student[3];

DCSD/DSE/DNE 18
Object Oriented Programming

Student nimal sunil kamal

age age=30 age=28 age=24

setAge(int) setAge(int) setAge(int) setAge(int)

setAge()

Class Object 1 Object 2 Object 3

Figure 1

Accessing Members

Members of the class can be accessed using relevant object. For an example, to call
function setAge() of nimal, it can be written as nimal.setAge(30).Then function setAge()
in object nimal is executing. In that time, function setAge() is using attribute age in object
nimal to set a value.

When we call kamal.setAge(32), the function setAge() in object kamal is executing and
the function setAge() uses attribute age in object sunil.

Format : name_of_the_class name_of_the_object;

Example : nimal.setAge(30); kamal.setAge(28);

DCSD/DSE/DNE 19
Object Oriented Programming

Private Functions

The functions which needs to be confidential to prevent access by outsiders should be kept as
private. The private functions of the class can be accessed by members of the class.

Example:

class Employee
{ private:
float basic_salary;
void getSalary();
public:
void setSalary(float);
};
void Employee :: getSalary()
{ cout<< basic_salary;
}
void Employee::setSalary(float basic_salary)
{ this-> basic_salary= basic_salary;
getSalary();
}
int main()
{ Employee a;
a. setSalary(50000);
return 0;
}

In this example, function getSalary() is private and it can be called by member function setSalary()
in the class. When this program is executing, it is calling function setSalary() in the object a. Then
function setSalary() in object a is executing and it is calling function getSalary() of same object
a.

DCSD/DSE/DNE 20
Object Oriented Programming

Static Members and Instance members

All the objects of the class share a static attribute. But every object of the class keeps own copy
of an instance attribute. The static function is used to access static attributes in the class.

Example : class Item


{ static float price;
int quantity;
public:
static void changePrice(float newprice);
void setQunatity(int quantity);

};
float Item :: price=50;

void Item :: setQuantity(int quantity)


{ this-> quantity= quantity;
}

int main()
{ Item:: changePrice(78);
Item x,y,z,
x. setQuantity(10);y. setQuantity(15);z. setQuantity(12);
}

in this example, prices of item objects x, y and z are 50 at the beginning. But quantities of item
objects x, y and z are sequentially10,15 and 12. The objects x, y and z are sharing attribute price
while objects x, y and z are keeping own copy of attribute quantity.

Attribute as an Array

Attribute(s) of a class can be represented using an array. For an example assume one employee in
a company has three telephone numbers to be represented. Here attribute telephone number can be
represented by an array with size 3.

DCSD/DSE/DNE 21
Object Oriented Programming

Example : class Employee


{ private:
long int telephone [3];

};

Objects as Function Arguments

The function(s) of a class can receive object(s) as arguments.


Example : class Student
{ private:
float age;
public:
void setAge (float age);
void compare (Student s);
};
void Student :: setAge (float age)
{ this-> age= age;
}
void Student ::compare (Student s)
{ if(age > s.age)
{ cout<<” a is taller than b “;
}
}
int main()
{ Student a,b;
a. setAge (6);
b. setAge (5);
a. compare(b);
return 0;
}

Here heights of student a and b are set by calling function setHeight() of each object. Then it calls
function compare() of object a and pass object b as an argument. it is received by object s of class
Student which is a parameter of function compare(). when the function compare() in object a is
executing, age refers to age of object a and s.age refers to age of object b.

DCSD/DSE/DNE 22
Object Oriented Programming

Return objects

A function in a class can return objects to the calling statement.


Example : class Account
{ private:
float balance;
public:
void setBalance(float balance);
Account addBalance (Account e);
void show();
};
void setBalance(float balance)
{ this-> balance= balance;
}
Account addBalance (Account e)
{ Account d;
d.balance=balance+e.balance;
return d;
}
void Account::show()
{ cout<<balance;
}
int main()
{ Account x,y;
x. setBalance(1500);y. setBalance(2500);
Account z;
z=x. addBalance(y);
z. show();
}

Here when it is executing statement z=x. addBalance(y), function addBalance of object x is


working. In this time balance refers to balance of object x and e.balance refers to balance of
object y. The sum of balances of objects x and y are stored in another object of class Account
called d. Then object d is returned by the function to the calling statement, x. addBalance(y) and
return values of the object are assigned to object z. The type of return object is class type Account.
Because of this, function type is also same type Account.

When statement z.show() is executing, it calls function show in object z and it is showing balance
in object z.

DCSD/DSE/DNE 23
Object Oriented Programming

Use of pointers

The members of the class can also be accessed through pointers created for members.

Example : class Student


{ public:
int age;
void setAge(int x);
};
int main()
{ Student a;
int Student::*t=&Student::age;
a.*t=12;
void (Student::*p) (int)=&Student::setAge;
(a.*p) (10);
return 0;
}
In this example, pointer *t is created to store address of attribute age and pointer *p is created to
store address of function void setAge(int x).

When it executes a.*t, it accesses age of object a through pointer *t.

When it executes (a.*p) (10), it calls function setAge() of object a through pointer *p and pass
value 10 to the parameter x of the function.

DCSD/DSE/DNE 24
Object Oriented Programming

Memory Allocation for Objects

In the case of allocating memory for objects created by class, Attributes of each object are allocated
separate memory space and same function in all objects is allocated one memory space.

Example: class Employee


{ float income;
int age;
public:
void setIncome();
void setAge();
}
int main()
{ Employee x,y;
return 0;
}

x.income y.income x.age y.age

x.setIncome() x.setAge()

y.setIncome() y.setAge()

Figure 2 Memory
Here attributes income and age of each object are allocated separate spaces in the memory. But
function setIncome() of objects x and y are allocated one space in the memory. Also function
setAge() of x and y objects are allocated one space in the memory.

DCSD/DSE/DNE 25
Object Oriented Programming

Lesson 4 - Constructors and Destructors

Introduction to Constructor

The constructor is a special function used in object-oriented programming. This is used to initialize
attributes of objects at the time of creating the objects. Due to application of constructor, objects
are set values at the time creating.

Format : class name_of_the_class


{ private : Attribute(s);
public:
name_of_the_constructor()
{ statements to initialize attributes
}
}
int main()
{ name_of_the_class name_of_the_object;
return 0:
}
Example : class Student
{ private : int age;
public:
Student ()
{ age=12;
}
};
int main()
{ Student nimal;
return 0:
}

DCSD/DSE/DNE 26
Object Oriented Programming

Features of constructor
The main features of constructor are listed below.
• Name of the constructor is class name.
• No return types.
• Write under public label.
• Automatically call at the time of creating an object.
• Can be parametrized.

Types of Constructors
Default constructor
The constructor which is not having parameters called Default constructor. It
assigns default values specified for attributes of the objects created by the class.

Example : class Student


{ private : int age;
public:
Student ()
{ age=12;
}
};
int main()
{ Student nimal, kamal;
return 0:
}
In this example ages of both nimal and kamal(objects) are set to 12. When object
nimal creates, age inside constructor refers to age of nimal. When object kamal
creates age inside the constructor refers to age of kamal.

DCSD/DSE/DNE 27
Object Oriented Programming

Parameterized constructor
The constructor which is having parameters called parameterized constructor. At
the time of creating objects, it passes values to the parameterized constructor.

Example : class Student


{ private : int age;
public:
Student (int age)
{ this->age=age;
}
};
int main()
{ Student nimal(15),kamal(18);
return 0:
}
In this example, when objects nimal, kamal creat, values 15 and 18 passes to the
parameterized constructor. Then age of nimal is set to 15 and age of kamal is set to
18. When the object nimal creates, age inside constructor refers to age of nimal and
at the time of creating object kamal,age inside constructor refers to age of kamal.

DCSD/DSE/DNE 28
Object Oriented Programming

Copy constructor
The constructor which is copying values of one object to another object is called
copy constructor.

Example : class Student


{ private : int age;
public:
Student (int age)
{ this->age=age;
}
Student (Student &s)
{ age=s.age;
}
};
int main()
{ Student nimal(15);
Student kamal(nimal);
return 0:
}

In this example, when object nimal creates, it automatically calls parametrized


constructor and, in this time, age inside parameterized constructor refers to age of
nimal.it sets age of nimal to 15. It identifies relevant constructor to be called by
matching parameters (parameter type and number of parameters).

When object kamal creates, it automatically calls copy constructor and it this time
age inside copy constructor refers to age of Kamal. It passes address of the object
nimal to the parameter s of Student type in copy constructor. After that it copies
value of nimal’s age to age of kamal through copy constructor parameters s.

DCSD/DSE/DNE 29
Object Oriented Programming

Introduction to Destructor

The destructor is a function in object-oriented programming which is used to deallocate memory


spaces allocated for objects when program execution is going out of objects’ scopes.

Example : class Student


{ private : int age;
public:
Student ()
{ age=12;
}
~Student ()
{ cout<<” End of the execution “;
}
};
int main()
{ Student nimal;
return 0:
}

In this example, when program execution goes out of the scope, it calls destructor and display
message as “End of the execution”.

DCSD/DSE/DNE 30
Object Oriented Programming

Features of Destructor

The following are main features of destructor.


• Name is the class name.
• No parameters are allowed.
• Keep under public section.
• Automatically call, when program execution goes out of the object.

DCSD/DSE/DNE 31
Object Oriented Programming

Lesson 5 – Inheritance

Introduction

Inheritance is one class re-using members (Attributes/Functions) of another class. The class which
provides members to other class called Super class (Parent Class). The class which receives
members is called Sub class (Child Class). There should be an IS-A relationship between super
and sub class. Private members of the super class are not inherited to sub class.

Format: class name_of_the_super_class


{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class name_of_the_sub_class : visibility_label name_of_the_super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

Benefits of inheritance

The following are some benefits of inheritance.


• Save memory space.
• Save programming time.
• Save programming effort.
• Use of code reliability.

Protected Label

The members (Attributes) which keep under label protected are accessed by members of the
super class and members of the sub class only. Nonmembers of the super class or sub class are
unable to use members under protected label.

DCSD/DSE/DNE 32
Object Oriented Programming

Inheritance Modes
Public Inheritance

Here protected members of the super class become protected members of the
sub class and public members of the super class become public members of the
sub class.

Protected: Protected:

int x int x

Public: Public:

int y int y

Super Class Sub Class

Figure 1

Private Inheritance

Here protected members and public members of the super class become private
members of the sub class.

Protected: private:

int x int x

Public: int y

int y

Super Class Sub Class


Figure 2

DCSD/DSE/DNE 33
Object Oriented Programming

Protected Inheritance

Here protected members and public members of the super class become
protected members of the sub class.

Protected: Protected:

int x int x

Public: int y

int y

Super Class Sub Class

Figure 3

Inheritance Example

Example: class Employee


{ protected:
float basic_salary;
public:
void setBasicSalary(float);
};
class Manager : public Employee
{ private:
float monthly_allowance;
public:
void setAllowance(float);
void findIncome();
};
void Employee::setBasicSalary(float basic_salary)
{ this->basic_salary= basic_salary;
}
void Manager::setAllowance(float monthly_allowance)
{ this-> monthly_allowance= monthly_allowance;
}
void Manager:: findIncome()
{ cout<< basic_salary+ monthly_allowance;
}
int main()
{ Manager saman;

DCSD/DSE/DNE 34
Object Oriented Programming

saman. setBasicSalary(25000);
saman. setAllowance(15000);
saman. findIncome();
}

• In this example, class Manager can re-use members of super class. It means attribute
basic_salary and function setBasicSalary() become members of the sub class.
• Here inherited mode is public. So protected member basic_salary becomes protected
member of sub class and public member setBasicSalary() becomes public member of sub
class.
• The function findIncome() of sub class Manager reuses attribute basic_salary of super
class.
• The object saman is reuses function setBasicSalary() through class Manager to set basic
salary of the manager saman.

Inheritance with Constructors

Constructors are unable to inherit by sub classes. But constructors can be used in inheritance
applications.

Example: class Employee


{ protected:
float basic_salary;
public:
Employee(float);
};
class Manager : public Employee
{ private:
float monthly_allowance;
public:
Manager(float);
void findIncome(); };
void Employee:: Employee(float basic_salary)

DCSD/DSE/DNE 35
Object Oriented Programming

{ this->basic_salary= basic_salary;
}

void Manager:: Manager(float basic_salary ,float monthly_allowance) : Employee(salary)


{ this-> monthly_allowance= monthly_allowance;
}
void Manager:: findIncome()
{ cout<< basic_salary+ monthly_allowance;
}
int main()
{ Manager saman(25000,15000);
saman. findIncome();
}

Here each class has a constructor to set values of attributes in each class. When it creates object
saman of class Manager, it calls subclass constructor and values are passed to the parameters in
the subclass. Value 2500 is passed to parameter basic_salary and value 15000 is passed to
parameter monthly_allowance in sub class constructor.

Sub class constructor calls super class constructor and relevant value(s) are passed to parameters
in super class constructor. Then value 25000 which received by parameter basic_salary in sub
class constructor, is passed the parameter basic_salary in super class constructor.

DCSD/DSE/DNE 36
Object Oriented Programming

Forms of Inheritance

There are different forms of inheritance available as shown below.

Figure 4 - Forms of inheritance

Single
One super class is inherited by one sub class.
Format: class super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

DCSD/DSE/DNE 37
Object Oriented Programming

Multiple
Several super classes are inherited by one sub class.
Format: class super_class1
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class super_class2
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

class sub_class : visibility_label super_class1, visibility_label super_class2


{ Access Label:
Attribute(s) ;
Functions(s) ;
};

Here constructors of the super classes are called according to the sequence we arrange
inheritance relationships. Here super class1 constructor is called first. Next super class2
constructor is called.

Hierarchical
One super class is inherited by several sub classes.
Format: class super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class1 : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class2 : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

DCSD/DSE/DNE 38
Object Oriented Programming

Multilevel
A derived class is inherited by another derived class.
Format: class super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class1 : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class2 : visibility_label sub_class1
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

Hybrid
More than one inheritance types available.
Format: class super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class1 : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class2 : visibility_label super_class
{ Access Label:
Attribute(s) ;
Functions(s) ;
};
class sub_class3 : visibility_label sub_class1, visibility_label sub_class2
{ Access Label:
Attribute(s) ;
Functions(s) ;
};

DCSD/DSE/DNE 39
Object Oriented Programming

Lesson 6 - Polymorphism

Introduction

The term polymorphism refers to use one name and perform many different tasks. This is one of
the object-oriented features. Using this feature, it is possible to write object-oriented applications
which one name is used for several behaviors.

Types of polymorphism

o Compile Time Polymorphism

Here the function to be called is identified at the time of compiling the program.

Examples : Function Overloading

Operator Overloading

o Run Time Polymorphism

Here the function to be called is identified at the time of running the program.

Examples : Virtual Function

Pure virtual function.

Function Overloading
Function overloading refers more than one function having same name with different parameter
list.

Format : class Name_of_the_class


{ function_1(parameters);
function_1(parameters);
function_1(parameters);
};

DCSD/DSE/DNE 40
Object Oriented Programming

Example : class Student


{ public:
void show();
void show(int);
void show(double);
};
void Student::show()
{ cout<<”I am a student”;
}
void Student::show(int age)
{ cout<<”My age is “<<age;
}
void Student ::show(double height)
{ cout<<”My height is “<<height;
}
int main()
{ Student amal;
amal. show();
amal. show(19);
amal.show(5.5);
}
In this example, each calling statement calls the relevant function by matching types and number
of parameters in the function heading.

DCSD/DSE/DNE 41
Object Oriented Programming

Operator Overloading
Operator overloading refers to providing different meanings for existing operators in C++. There
are few operators which are unable to overload. These are;

Scope operator ::
sizeof
member selector .
member pointer selector *
ternary operator ?:

Format : class Name_of_the_class


{ operator_function operator_symbol(parameters);
};
Example : class Graph
{ int x;
public:
Graph(int);
void operator - ();
void show();
};
Graph :: Graph(int x)
{ this-> x= x;
}
void Graph::operator - ()
{ x= - x;
}
void Graph::show()
{ cout<< x;
}
int main()
{ Graph graph1 (20);
-graph1;
graph1. show();
return 0;
}
In this example, operator overloading function converts value of x in object graph1 to minus value.
The statement -graph1 in main function calls operator function in the class Graph.

DCSD/DSE/DNE 42
Object Oriented Programming

Virtual Function
Virtual function refers to a function in super class which is overridden by sub class. This helps sub
class to provide different definition of super class function. The keyword virtual is directed to
execute the overridden function in sub class instead of super class version. The following are
important points on virtual function in C++.They are,

• Virtual function should be a member of a class.


• Virtual function cannot be static.
• Virtual function should be accessed using pointer or reference of base class.
• Prototype of the virtual function should be same in derived class as in base class.
• There is no virtual destructor. But virtual constructor is there.

Format : class superclass


{ virtual function1(parameters);
};
class subclass : public superclass
{ function1(parameters);
};

DCSD/DSE/DNE 43
Object Oriented Programming

Example : class Student


{ virtual void show();
};
class PrimaryStudent : public Student
{ void show();
};
void Student::show()
{ cout<<”I am a student “;
}
void PrimaryStudent::show()
{ cout<<”I am a primary student “;
}
int main()
{ PrimaryStudent sahan;
Student *st;
st=& sahan;
st->show();
return 0;
}
In this example, function void show() in super class student is overridden in class primary student.
Super class pointer object has been assigned object sahan of the sub class. When it executes
statement st->show() , it calls show function in sub class.it decides which function show() is called
looking at the pointer value during running time. Here behavior of the sub class function show()
is different compared to super class function show().

Pure Virtual Function


Pure Virtual function refers to a function in super class which is not having function definition.
Here function heading is assigned 0 to indicate that it is not having function definition.

Format : class superclass


{ virtual function1(parameters)=0;
};
class subclass : public superclass
{ function1(parameters);
};

DCSD/DSE/DNE 44
Object Oriented Programming

Example : class Student


{ virtual void show()=0;
};
class PrimaryStudent : public Student
{ void show();
};
void PrimaryStudent::show()
{ cout<<”I am a primary student “;
}
int main()
{ PrimaryStudent sahan;
Student *st;
st=& sahan;
st->show();
return 0;
}

In this example, pure virtual function void show() in super class student is overridden in class
primary student. Super class pointer object has been assigned object sahan of the sub class. When
it executes statement st->show() , it calls show function in sub class.it decides which function
show() is called looking at the pointer value during running time. Here sub class has added function
behavior for function show() by overriding.

DCSD/DSE/DNE 45
Object Oriented Programming

Lesson 7 - File Operation

Introduction
• Many real-life problems handle large volumes of data and in such situations, we need to
use some secondary storage devices such as hard disk to store the data.
• The data is stored in these devices using the concept of files.
• A file is a collection of related data stored in a particular area on the disk.
• Programs can be designed to perform the read and write operations on these files.
• The I/O system of C++ handles file operations which are very much similar to the console
input and output operations.
• It uses file streams as an interface between the programs and the files.
• The stream that supplies data to the program is known as input stream and the one that
receives data from the program is known as output stream.
• The input operation involves the creation of an input stream and linking it with the program
and the
• T output operation involves establishing an output stream with the necessary links with the
program and the output file.

Figure 5 - File input and output streams

DCSD/DSE/DNE 46
Object Oriented Programming

Working with single files

Opening Files Using open()


The function open() can be used to open multiple files that use the same stream object. For
example, we may want to process a set of files sequentially. In such cases, we may create a single
stream object and use it to open each file in turn. This is done as follows:

file-stream-class stream-object;
stream-object.open (“filename”);

Example:
ofstream outfile; // Create stream (for output)
outfile.open(“DATA1”); // Connect stream to DATA1
.....
.....
outfile.close(); // Disconnect stream from DATA1
outfile.open(“DATA2”); // Connect stream to DATA2
.....
.....
outfile.close(); // Disconnect stream from DATA2
.....
.....

DCSD/DSE/DNE 47
Object Oriented Programming

Example - Program
# include <iostream.h>
# include <fstream.h>
void main()
{
char name[10];
float price;
ofstream outf("ITEM");
cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";
outf << price << "\n";
outf.close();
ifstream inf("ITEM");
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
inf.close();
}

DCSD/DSE/DNE 48
Object Oriented Programming

Another Example with while loop:

void main()
{ char name[10], response;
float price;
ofstream outf("ITEM");
do
{ cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";
outf << price << "\n";
cout << "\nDo u want to add another record (y/n) : "; cin >> response;
} while(response=='y');
outf.close();
ifstream inf("ITEM");
while(inf)
{
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
}
inf.close();
}

Detecting End-Of-File - while(inf)


Detection of the end-of-file condition is necessary for preventing any further attempt to read data
from the file. An ifstream object, such as inf, returns a value of 0 if any error occurs in the file
operation including the end-of-file condition. Thus, the while loop terminates when inf returns a
value of zero on reaching the end-of-file condition.

DCSD/DSE/DNE 49
Object Oriented Programming

Working with multiple files

Example:
# include <iostream.h>
# include <fstream.h>
void main()
{ char name[10];
float price;
ofstream outf;
outf.open("EXPENSIVE");
cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";
outf << price << "\n";
outf.close();

ifstream inf;
inf.open("EXPENSIVE");
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
inf.close();

outf.open("CHEAP");
cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";

DCSD/DSE/DNE 50
Object Oriented Programming

outf << price << "\n";


outf.close();
inf.open("CHEAP");
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
inf.close();
}

Another Example with while loop:

# include <iostream.h>
# include <fstream.h>
void main()
{ char name[10],response;
float price;
ofstream outf;
outf.open("EXPENSIVE");
do
{ cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";
outf << price << "\n";
cout << "\nDo u want to enter another record (y/n) : "; cin >> response;
} while (response =='y');
outf.close();
ifstream inf;

DCSD/DSE/DNE 51
Object Oriented Programming

inf.open("EXPENSIVE");
cout << "\nExpensive Items ";
while(inf)
{
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
}
inf.close();
outf.open("CHEAP");
do
{
cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
outf << name << "\n";
outf << price << "\n";
cout << "\nDo u want to enter another record (y/n) : "; cin >> response;
} while (response =='y');
outf.close();
inf.open("CHEAP");
cout << "\nCheap Items ";
while(inf)
{
inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;

DCSD/DSE/DNE 52
Object Oriented Programming

}
inf.close();
}

Working with multiple files simultaneously


Example :

# include <iostream.h>
# include <fstream.h>
void main()
{
char name[10],response;
float price;
ofstream oute, outc;
oute.open("EXPENSIVE");
outc.open("CHEAP");
do
{ cout << "\nEnter item name : "; cin >> name;
cout << "\nEnter item price : "; cin >> price;
if (price > 100)
{ oute << name << "\n";
oute << price << "\n";
}
else
{ outc << name << "\n";
outc << price << "\n";
}
cout << "\nDo u want to enter another record (y/n) : "; cin >> response;

DCSD/DSE/DNE 53
Object Oriented Programming

} while (response =='y');


oute.close();
outc.close();
ifstream inf;
inf.open("EXPENSIVE");
cout << "\nExpensive Items ";
while(inf)
{ inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
}
inf.close();
inf.open("CHEAP");
cout << "\nCheap Items ";
while(inf)
{ inf >> name;
inf >> price;
cout << "\nItem name : " << name;
cout << "\nItem price : " << price;
}
inf.close();
}

DCSD/DSE/DNE 54
Object Oriented Programming

File Modes
• Creating a stream using ifstream implies input and creating a stream using ofstream implies
output. So in these cases it is not necessary to provide the mode parameters.
• The fstream class does not provide a mode by default and therefore, we must provide the
mode explicitly.
• Following is the list of file mode parameters and their meaning.

Parameter Meaning

ios::app Append to end-of-file

ios::ate Go to end-of-file on opening

ios::binary Binary file

ios::in Open file for reading only

ios::nocreate Open fails if the file does not exist

ios::noreplace Open fails if the file already exists

ios::out Open file for writing only

ios::trunc Delete contents of the file if it exists

• Examples:
◼ fstream file;
file.open(“ITEM”,ios::in)
◼ fstream file;
file.open(“ITEM”,ios::app)
◼ fstream file;

DCSD/DSE/DNE 55
Object Oriented Programming

file.open(“ITEM”,ios::out)
◼ fstream file;
file.open(“ITEM”,ios::app | ios::nocreate)

Working with Classes and Files


• Example
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
class Inventory
{
char name[20];
int code;
float cost;
public:
void readdata();
void writedata();
};
void Inventory::readdata()
{
cout<<"Enter Name : "; cin>>name;
cout<<"Enter Code : "; cin>>code;
cout<<"Enter Cost : "; cin>>cost;
}
void Inventory::writedata()
{
cout<<setw(15)<<name<<setw(15)<<code<<setw(15)<<cost<<"\n";
}

DCSD/DSE/DNE 56
Object Oriented Programming

int main()
{
Inventory item[3];

fstream file;
file.open("Stock.txt",ios::in | ios::out);
cout<<"Enter Details for three Items \n";
for(int i=0;i<3;i++)
{
item[i].readdata();
file.write((char *) & item[i],sizeof(item[i]));
}
file.seekg(0);
cout<<"\n Output \n";
for(int i=0;i<3;i++)
{
file.read((char *) & item[i],sizeof(item[i]));
item[i].writedata();
}
file.close();
}

DCSD/DSE/DNE 57
Object Oriented Programming

File Pointers

“ITEM” file

input pointer Apple


Open for reading only ( get pointer ) 50
Grape“ITEM” file
40

Apple

output pointer 50
Open in append mode
( put pointer ) Grape
( for writing more data )
40

“ITEM” file
output pointer
Open for writing only
( put pointer )

Manipulation of File Pointers


• The File Stream Classes support the following functions to manage the file pointers:
◼ seekg()- Moves get pointer (input) to a specified location
◼ seekp() - Moves put pointer (output) to a specified location
◼ tellg() - Gives the current position of the get pointer
◼ tellp() - Gives the current position of the put pointer
• Examples:
◼ fstream file;
file.open(“ITEM”,ios::in);
file.seekg(10);
// This will move the get pointer (input) to byte number 10.

DCSD/DSE/DNE 58
Object Oriented Programming

// The bytes in a file are numbered from zero.


// Therefore, the pointer will be pointing to the 11th byte.
• Examples:
◼ fstream file;
file.open(“ITEM”,ios::app);
int p = file.tellp();
// Here, the output pointer is moved to the end of the file and the
// value of p will represent the number of bytes in the file.
◼ fstream file;
file.open(“ITEM”,ios::in);
int p = file.tellp();

// p =???

• Specifying the offset:

Figure 6 - Action of single argument seek function

• ‘Seek’ functions seekg() and seekp() can also be used with two arguments as
follows:
• seekg(offset,refposition);
• seekp(offset,refposition);
• The refposition takes one of the following three constants defined in the ios class:
◼ ios::beg - start of the file

DCSD/DSE/DNE 59
Object Oriented Programming

◼ ios::cur - current position of the pointer


◼ ios::end - End of the file

• Some ‘seek’ examples:


◼ file.seekg(0,ios::beg); - Go to the start
◼ file.seekg(0,ios::cur); - Stay at the current position
◼ file.seekg(0,ios::end); - Go to the end of the file
◼ file.seekg(m,ios::beg); - Go to the (m+1)th byte in the file
◼ file.seekg(m,ios::cur); - Go forward m bytes from the
current position
◼ file.seekg(-m,ios::cur); - Go backward m bytes from the
current position
◼ file.seekg(-m,ios::end); - Go backward m bytes from the end

DCSD/DSE/DNE 60
Object Oriented Programming

References

E Balagurusamy (2014) Object oriented programming with c++, NEW DELHI: McGraw Hill Education (India)
Private Limited.

javatpoint (2018) C++ Inheritance, Available at: https://www.javatpoint.com/cpp-inheritance (Accessed: 27 - 07


- 2020).

programiz (2019) C++ Examples, Available at: https://www.programiz.com/cpp-


programming/examples (Accessed: 27 - 07 - 2020).

codebind (2019) C++ Programs and Examples | C++ Samples, Available at: http://www.codebind.com/cpp/cpp-
programs-examples/ (Accessed: 28 - 07 - 2020).

codescracker (2019) C++ Programming Examples, Available at: https://codescracker.com/cpp/program/cpp-


programming-examples.htm (Accessed: 29 - 07 - 2020).

DCSD/DSE/DNE 61

You might also like