Professional Documents
Culture Documents
E Book OOP (Object Oriented Programming)
E Book OOP (Object Oriented Programming)
Table of Contents
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
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.
#include <iostream>
using namespace std;
int main()
{ cout << “C++ is better than C.\n”; //This is a output
return 0;
}
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
Tokens
DCSD/DSE/DNE 6
Object Oriented Programming
Keywords
• The keywords are reserved words in programming use to perform special functionalities.
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
Punctuators
Operators
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++.
Table 2
DCSD/DSE/DNE 9
Object Oriented Programming
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.
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.
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.
int x;
t=&x;
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.
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.
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++
DCSD/DSE/DNE 13
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.
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).
Functions : walk ()
eat ()
Example : Object: Saman
Attributes : age = 18
weight = 5.8
Functions : walk ()
eat ()
DCSD/DSE/DNE 14
Object Oriented Programming
• 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
3. Inheritance
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
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.
DCSD/DSE/DNE 17
Object Oriented Programming
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.
DCSD/DSE/DNE 18
Object Oriented Programming
setAge()
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.
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
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.
};
float Item :: price=50;
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
};
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
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.
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
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.
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
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.
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.
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.
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.
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
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
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.
Benefits of inheritance
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
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
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
Figure 3
Inheritance Example
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.
Constructors are unable to inherit by sub classes. But constructors can be used in inheritance
applications.
DCSD/DSE/DNE 35
Object Oriented Programming
{ this->basic_salary= basic_salary;
}
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
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) ;
};
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
Here the function to be called is identified at the time of compiling the program.
Operator Overloading
Here the function to be called is identified at the time of running the program.
Function Overloading
Function overloading refers more than one function having same name with different parameter
list.
DCSD/DSE/DNE 40
Object Oriented Programming
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 ?:
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,
DCSD/DSE/DNE 43
Object Oriented Programming
DCSD/DSE/DNE 44
Object Oriented Programming
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
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.
DCSD/DSE/DNE 46
Object Oriented Programming
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
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();
}
DCSD/DSE/DNE 49
Object Oriented Programming
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
# 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();
}
# 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
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
• 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)
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
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 )
DCSD/DSE/DNE 58
Object Oriented Programming
// p =???
• ‘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
DCSD/DSE/DNE 60
Object Oriented Programming
References
E Balagurusamy (2014) Object oriented programming with c++, NEW DELHI: McGraw Hill Education (India)
Private Limited.
codebind (2019) C++ Programs and Examples | C++ Samples, Available at: http://www.codebind.com/cpp/cpp-
programs-examples/ (Accessed: 28 - 07 - 2020).
DCSD/DSE/DNE 61