SESSION-2019-20 STUDY MATERIAL FRAGMENT 1 SUBJECT: COMPUTER SCIENCE CHAPTERS INCLUDED: Chapter 2: Object Orientated Programming Chapter 3: Function Overloading Chapter 4: Class and Objects Chapter 5: Constructors and Destructors Chapter 6: Inheritance-Extending Classes Chapter 7: Data File Handling TEACHERS’ CONTRIBUTORS: MOHIT TANDON,PGT COMPUTER SCIENCE, SECTOR-D NEERU NIGAM,PGT COMPUTER SCIENCE, SECTOR-I GAJENDRA SINGH DHAMI, PGT COMPUTER SCIENCE, SOUTH-CITY
80
Embed
SESSION-2019-20 STUDY MATERIAL FRAGMENT 1 SUBJECT ...southcity.thelps.edu.in/UploadedFiles/UpdateDirectory/Study Materia… · Study Material - CS-XII Chap - 3 : Object Oriented Programming
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Study Material - CS-XII Chap - 3 : Object Oriented Programming 1
CHAPTER – 3: OBJECT ORIENTED PROGRAMMING CONCEPTS
Object Oriented Programming follows bottom up approach in program design and emphasizes on safety and security of data..
FEATURES OF OBJECT ORIENTED PROGRAMMING:
Inheritance: Inheritance is the process of forming a new class from an existing class or base class. The base
class is also known as parent class or super class. Derived class is also known as a child class or sub class. Inheritance helps in
reusability of code , thus reducing the overall size of the program
Data Abstraction: It refers to the act of representing essential features without including the background details
.Example : For driving , only accelerator, clutch and brake controls need to be learnt rather than working of engine and other details.
Data Encapsulation: It means wrapping up data and associated functions into one single unit called class.. A class groups its members into three sections :public, private and protected, where private
and protected members remain hidden from outside world and thereby helps in implementing data hiding.
Modularity :
The act of partitioning a complex program into simpler fragments called modules is called as modularity.
It reduces the complexity to some degree and
It creates a number of well defined boundaries within the program .
Polymorphism: Poly means many and morphs mean form, so polymorphism means one name multiple forms. It is the ability for a message or data to be processed in more than one form. C++ implements Polymorhism through Function Overloading , Operator overloading and
Virtual functions .
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 3 : Object Oriented Programming 2
Study Material - CS-XII Chap - 3 : Object Oriented Programming 2
.
SHAPE
area()
RECTANGLE() TRIANGLE() CIRCLE()
area(rectangle) Area(triangle) Area(circle)
SOLVED QUESTIONS
Q1. Discuss major OOP concepts briefly.
Ans. Following are the general OOP concepts: 1. Data Abstraction: Data abstraction means, providing only essential information to the outside word and hiding their background details i.e. to represent the needed information in program without presenting the details. 2. Data Encapsulation: The wrapping up of data and operations/functions (that operate on the data) into a single unit (called class) is known as Encapsulation. 3. Modularity: Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules. 4. Inheritance: Inheritance is the capability of one class of things to inherit capabilities or properties from another class. 5. Polymorphism: Polymorphism is the ability for a message or data to be processed in more than one form. Q2. What are programming paradigms? Give names of some popular programming paradigms.
Ans. Programming Paradigm: A Programming Paradigm defines the methodology of designing and implementing programs using the key features and building blocks of a programming language. Following are the different programming paradigms: (i) Procedural Programming (ii) Object Based Programming (iii) Object Oriented Programming Q3. What are the shortcomings of procedural and modular programming approaches?
Ans. Following are the various shortcomings of procedural and modular programming approaches: Procedural Programming is susceptible to design changes. Procedural Programming leads to increased time and cost overheads during design changes. Procedural and Modular programming both are unable to represent real world relationship that exists among objects.
Study Material - CS-XII Chap - 3 : Object Oriented Programming 3
Study Material - CS-XII Chap - 3 : Object Oriented Programming 3
In modular programming, the arrangement of the data can’t be changed without modifying all the functions that access it. Q4. Write a short note on OO programming.
Ans. OOP stands for Object Oriented Programming. In, Object-Oriented Programming (OOP), the program is organized around the data being operated upon rather than the operations performed. The basic idea behind OOP is to combine both, data and its functions that operate on the data into a single unit called object. Following are the basic OOP concepts:
1. Data Abstraction 2. Data Encapsulation 3. Modularity 4. Inheritance 5. Polymorphism
Q5. What is the significance of private, protected and public specifiers in a class?
Ans. A class groups its members into three sections: private, protected, and public. The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding. The public members are accessible everywhere in a program.
ASSIGNMENT
Problem 1: What do you understand by Polymorphism? Give an example in C++ to show its implementation in C++.
Problem 2: What do you understand by Data Encapsulation and Data Hiding?
Problem 3: What is Inheritance? Give an example in C++ to show its implementation in C++.
Problem 4: Illustrate the concept of Inheritance with the help of an example.
Problem 5: Encapsulation is one of the major properties of OOP. How is it implemented in C++? Problem 6: Reusability of classes is one of the major properties of OOP. How is it implemented in
C++? Problem 7: Define the term Data Hiding in the context of Object Oriented Programming. Give a
suitable example using a C++ code to illustrate the same.
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 1 of 6
Notes by:
Neeru Nigam,PGT(CS)
LPS, Sector-I
Chapter 3:Function overloading
It is also known as “Polymorphism”, one of the strongest features
of the Object Oriented Programming Structure. The meaning of Function
overloading is :- the same function can be used differently at different places,
within the same program. That means, we chose one name of the function, but
the function carries different prototypes and definitions , within the same
program.
In general, when we declare an user-defined function, we have to follow
the prototype within the program, number of times we call the function. If we
don’t follow the prototype, we get an error message (Prototype mismatch,
during compliation ) . But because of function overloading feature, we can have
different definitions and different prototypes of the same function in same
program.
We try to understand the above explanation, with the help of an example:
EXAMPLE OF FUNCTION OVERLOADING :
int AREA( int s ) // function 1//
{
return s*s;
}
int AREA ( int l, int b ) // function 2 //
{
return l*b;
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 2 of 6
}
float AREA(int a, int b, int c ) // function 3 //
{
float s, ar;
s=(a+b+c)/2;
ar=sqrt((s*(s-a)*(s-b)*(s-c));
return ar;
}
In the above example , we can see there are three definitions given for the user-
defined function AREA. The first definition has only one parameter, and is
returning the area of a square. The second definition of the function AREA,
carrying two parameters and is returning the area of a rectangle, while the third
definition of the function AREA, is having three parameters and is returning the
area of a triangle.
ADVANTAGE :
As we can understand from the above example, that to get the area of
square, rectangle and triangle, we donot need to declare three different functions
with different names, and more importantly , we are not supposed to write three
programs. We can get the area of our desired shape, according to our need, that
too, within the same program
SOME QUESTIONS :
Q.1 Which function is called during each function call in the program
given below:
int sum (int x); // function 1 //
char choice ( char a , char b ); // function 2 //
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 3 of 6
char choice ( char a ); // function 3 //
float sum( int x, float y); // function 4 //
void main ( )
{
int n;
char ch,ch1;
float n1;
sum(n); // call 1 //
choice(ch); // call 2 //
choice( ch,ch1); // call 3 //
sum (n,n1); // call 4 //
}
Answer :
Call 1 invoke function 1
Call 2 invoke function 3
Call 3 invoke function 2
Call 4 invoke function 4
Q.2 Write the prototype of the overloaded function called sum( ) that add rwo
integers and return an integer, that add two double precision quantity and return
double precision quantity, that add one float and one integer and return float
quantity.
Ans. int SUM ( int , int );
double SUM ( double, double );
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 4 of 6
float SUM ( float, int );
Q.3 What will be the output of the following program :
#include < iostream.h>
int area ( int s )
{
return ( s * s );
}
float area ( int b , int h )
{
return (.5 * b* h );
}
void main ( )
{
cout << area (5)<< endl;
cout<<area(4,3)<< endl;
cout<<area(6,area(3))<<endl;
}
Ans : The output will be:
25
6
27
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 5 of 6
Q.4 Write the output of the following program : ( ASSIGNMENT )
class x
{
void print ( double )
{
cout<<”double”<<endl;
}
void print ( int )
{
cout<<”int”<<endl;
}
void print ( void * )
{
cout<< “void * “<<endl;
}
};
void main ()
{
X obj;
char ch=’A’;
int num=66;
float pi=3.14;
XII-CS-NOTES CHAPETER 3:FUNCTION OVERLOADING Page 6 of 6
char st[]=”ASTRING”;
obj.print(ch);
obj.print(pi);
obj.print(st);
obj.print(num);
}
Q.6 Write declaration of a function COMPOUND_INTREST, having
parameters ( for four different declarations ), illustrating the objective of
function overloading :
1. long p , int T
2. long P , Int T, float r
3. long P, float r
4. int t
NOTE :
When we give more than one declarations of constructor of a class, it is
known as “ Constructor overloading “
Study Material - CS-XII Chap - 4 : Classes and Objects 1
CHAPTER – 4: CLASSES AND OBJECTS
The major components of Object Oriented Programming are . Classes & Objects
A Class is a group of similar objects . Objects share two characteristics: They all have state and
behavior. For example : Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current
speed) and behavior (changing gear, applying brakes). Identifying the state and behavior for real-
world objects is a great way to begin thinking in terms of object-oriented programming. These
real-world observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages)
and exposes its behavior through functions
Classes in Programming :
It is a collection of variables, often of different types and its associated functions.
Class just binds data and its associated functions under one unit there by enforcing
encapsulation.
Classes define types of data structures and the functions that operate on those
data structures.
A class defines a blueprint for a data type.
Class Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations.
class <class_name> {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members that can either be data or function declarations, and optionally access specifiers.
[Note: the default access specifier is private.]
Example : class Box
{ int a;
public:
double length; // Length of a box
double breadth; // Breadth of a box
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 4 : Classes and Objects 2
Study Material - CS-XII Chap - 4 : Classes and Objects 2
double height; // Height of a box
};
Access specifiers in Classes:
Access specifiers are used to identify access rights for the data and member functions of the class. There are three main types of access specifiers in C++ programming language:
private
public
protected
Member-Access Control
Type of Access
Private
Protected
Meaning
Class members declared as private can be used only by
member functions and friends (classes or functions) of the class.
Class members declared as protected can be used by member
functions and friends (classes or functions) of the class. Additionally,
they can be used by classes derived from the class.
Public Class members declared as public can be used by any function.
Importance of Access Specifiers
Access control helps prevent you from using objects in ways they were not intended to be used. Thus it helps in implementing data hiding and data abstraction.
OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented system.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:-
<Class_name> < object_name>;
In C++, a class variable is known as an object. The declaration of an object is similar to that of a variable of any data type. The members of a class are accessed or referenced
using object of a class.
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Both of the objects Box1 and Box2 will have their own copy of data members.
Study Material - CS-XII Chap - 4 : Classes and Objects 3
Study Material - CS-XII Chap - 4 : Classes and Objects 3
Accessing / calling members of a classAll member of a class are private by default. Private member can be accessed only by the function of the class itself.Public member of a class can be accessed through any object of the class. They are accessed or called using object of that class with the help of dot operator (.). The general syntax for accessing data member of a class is:-
Object_name.Data_member=value;
The general syntax for accessing member function of a class is:-
Object_name. Function_name (actual arguments);
The dot ('. ') used above is called the dot operator or class member access operator. The dot
operator is used to connect the object and the member function. The private data of a class can
be accessed only through the member function of that class.
Class methods definitions (Defining the member functions)
Member functions can be defined in two places:-
(I) Outside the class definition
The member functions of a class can be defined outside the class definitions. It is only
declared inside the class but defined outside the class. The general form of member function definition outside the class definition is:
Return_type Class_name:: function_name (argument list) { Function body
}
Where symbol :: is a scope resolution operator.
The scope resolution operator (::) specifies the class to which the member being declared
belongs, granting exactly the same scope properties as if this function definition was directly
included within the class definition
class sum
{
int A, B, Total;
public:
void getdata ();
void display ();
};
void sum:: getdata () // Function definition outside class definition Use of :: operator
{ cout<<” \n enter the value of A and B”; cin>>A>>B;
}
Study Material - CS-XII Chap - 4 : Classes and Objects 4
Study Material - CS-XII Chap - 4 : Classes and Objects 4
void sum:: display () // Function definition outside class definition Use of :: operator
{ Total =A+B;
cout<<”\n the sum of A and B=”<<Total; }
(II) Inside the class definition
The member function of a class can be declared and defined inside the class definition.
class sum
{
int A, B, Total;
public:
void getdata () { cout< ”\n enter the value of A and B”; cin>>A>>B;
}
void display ()
{ total = A+B; cout<<”\n the sum of A and B=”<<total; }
};
Difference between structure and class in C++
In C++, a structure is a class defined with the struct keyword.Its members and base classes
are public by default. A class defined with the class keyword has private members and base
classes by default. This is the only difference between structs and classes in C++.
INLINE FUNCTIONS
Inline functions definition starts with keyword inline
The compiler replaces the function call statement with the function code
itself(expansion) and then compiles the entire code.
They run little faster than normal functions as function calling overheads are saved.
A function can be declared inline by placing the keyword inline before it.
Example
inline void Square (int a)
{ cout<<a*a;
}
void main() {.
Square(4); { cout <<4*4;}
Square(8) ; { cout <<8*8; } }
In place of function call , function body is substituted because Square () is inline function.
Study Material - CS-XII Chap - 4 : Classes and Objects 5
Study Material - CS-XII Chap - 4 : Classes and Objects 5
Pass Object As An Argument
/*C++ PROGRAM TO PASS OBJECT AS AN ARGUMEMT. The program Adds the
Study Material - CS-XII Chap - 4 : Classes and Objects 7
Study Material - CS-XII Chap - 4 : Classes and Objects 7
} void
INTAX()
{ gets(Name);
cin>>PanNo>>Taxabi
ncm; CompTax(); } void OUTAX() { cout<<Name<<‟\n‟<<PanNo<<‟\n‟<<Taxabincm<<‟\n‟<<TotTax<<endl; } }; Q 2 : Define a class HOTEL in C++ with the following description:
Private Members
Rno //Data Member to store Room No
Name //Data Member to store customer Name
Tariff //Data Member to store per day charge
NOD //Data Member to store Number of days
CALC //A function to calculate and return amount as NOD*Tariff
and if the value of NOD*Tariff is more than 10000 then as 1.05*NOD*Tariff
Public Members:
Checkin( ) //A function to enter the content RNo,Name, Tariff and NOD
Checkout() //A function to display Rno, Name, Tariff, NOD
and Amount (Amount to be displayed by calling function
CALC( )
Solution : #include<iostream.h> class HOTEL {unsigned int Rno;
char
Name[25];
unsigned int
Tariff;
unsigned int
NOD; int
CALC() {int x; x=NOD*Tariff;
if( x>10000)
return(1.05*NOD*Ta
riff);
else
return(NOD*Tariff);
}
public:
void Checkin()
{cin>>Rno>>Name>>Tariff>>NOD;}
void Checkout()
{cout<<Rno<<Name<<Tariff<<NOD<<CALC();}
Study Material - CS-XII Chap - 4 : Classes and Objects 8
Study Material - CS-XII Chap - 4 : Classes and Objects 8
};
Q 3 Define a class Applicant in C++ with following description:
Private Members A data member ANo ( Admission Number) of type long
A data member Name of type stringA data member Agg(Aggregate Marks) of type float
A data member Grade of type charA member function GradeMe( ) to find the Grade as per the Aggregate Marks obtained by a student. Equivalent Aggregate marks range and the respective Grades are shown as follows
Aggregate Marks Grade > = 80 A
Less than 80 and > = 65 B
Less than 65 and > = 50 C
Less than 50 D
Public Members
A function Enter( ) to allow user to enter values for ANo, Name, Agg & call function GradeMe( ) to find the Grade
A function Result ( ) to allow user to view the content of all the data members.
Ans: class Applicant {long ANo;
char Name[25];
float Agg;
char Grade;
void GradeMe( )
{if (Agg > = 80)
Grade = „A‟;
else if (Agg >= 65 && Agg < 80 )
Grade = „B‟;
else if (Agg >= 50 && Agg < 65 )
Grade = „C;
else
Grade = „D‟; }
public: void Enter ( ) {cout <<”\n Enter Admission No. “; cin>>ANo;
cout <<”\n Enter Name of the Applicant “; cin.getline(Name,25);
cout <<”\n Enter Aggregate Marks obtained by the Candidate :“; cin>>Agg; GradeMe( );
Study Material - CS-XII Chap - 4 : Classes and Objects 10
Study Material - CS-XII Chap - 4 : Classes and Objects 10
cout<<"Price :";cout<<Price;
cout<<"Quantity :";cout<<Qty;
cout<<"Discount :";cout<<discount;
}
PRACTICE QUESTIONS
Q 1. Define a class employee with the following specifications :
Private members of class employee
empno integer
ename 20 characters
basic, hra, da netpay float
calculate() A function to calculate basic + hra + da with float return type
Public member function of class employee havedata() function to accept values for empno, sname, basic, hra, da and invoke
calculate() to calculate netpay. dispdata() function to display all the data members on the screen.
Q2. Define a class Student with the following specifications :
Private members :
roll_no integer
name 20 characters
class 8 characters
marks[5] integer
percentage float
Calculate() a function that calculates overall percentage of marks and return the
percentage of marks.
public members :
Readmarks() a function that reads marks and invoke the Calculate function.
Displaymarks() a function that prints the marks.
Q3. Define a class report with the following specification :
Private members :
adno 4 digit admission number
name 20 characters
marks an array of 5 floating point values
average average marks obtained function Getavg() to compute the average obtained in five subjects
Public members :
readinfo() function to accept values for adno, name, marks, and invoke the function getavg().
displayinfo() function to display all data members on the screen you should give function definitions.
Study Material - CS-XII Chap - 4 : Classes and Objects 11
Study Material - CS-XII Chap - 4 : Classes and Objects 11
Q4. Declare a class myfolder with the following specification :
Private members of the class
Filenames – an array of strings of size[10][25]( to represent all the names of files
inside myfolder) Availspace – long ( to represent total number of bytes available in myfolder) Usedspace – long ( to represent total number of bytes used in myfolder)
Public members of the class
Newfileentry() – A function to accept values of Filenames, Availspace and
Usedspace fromuser Retavailspace() – A Fucntion that returns the value of total Kilobytes
available ( 1 Kilobytes = 1024 bytes) Showfiles() – a function that displays the names of all the files in myfolder
ASSIGNMENT
1. What is relation between class and object?
2. What are inline functions? Give example
3. Difference between private & public access specifiers.
4. How class implements data-hiding & encapsulation?
5. What is the difference between structure and a class ?
6. How is inline function different from a normal function ?
7. Rewrite the following C++ code after removing the syntax error(s) (if any). Underline each correction. include<iostream.h> class FLIGHT{ long FlightCode; char Description[25]; public: void AddInfo() { cin>>FlightCode; gets(Description); } void ShowInfo() { cout<<FlightCode<<":" <<Description<<endl; } };
Study Material - CS-XII Chap - 4 : Classes and Objects 12
Study Material - CS-XII Chap - 4 : Classes and Objects 12
8. Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. #include[iostream.h] #include[stdio.h] class Employee { int EmpId=901; char EName[20]; public: Employee() {} void Joining() { cin>>EmpId; gets(EName); } void List() { cout<<EmpId<<":" <<EName<<endl; } } void main(){ Employee E; Joining.E(); E.List(); }
9. Identify the error(s) in the following code fragment: class X{ int a b; void count(void) { a++; } public: int x; void init(int,int,int); void print(void);
Study Material - CS-XII Chap - 4 : Classes and Objects 13
Study Material - CS-XII Chap - 4 : Classes and Objects 13
10. Define a class to represent batsmen in a cricket team. Include the following members: Data Members: First name, Last name, Runs made, Number of fours, Number of sixes Member Functions: (i) To assign the initial values (ii) To update runs made (It should simultaneously update fours and sixes, if required). (iii) To display the batsman’s information Make appropriate assumptions about access labels.
11. Define a class student with the following specifications: private members of class student admno integer sname 20 characters
Study Material - CS-XII Chap - 4 : Classes and Objects 14
Study Material - CS-XII Chap - 4 : Classes and Objects 14
eng, math, science float total float ctotal() A function to calculate eng + math + science with float return type public member functions of class student Takedata() function to accept values for admno, sname, eng, math, science and ivoke ctotal() to calculate total. Showdata() function to display all the data members on the screen.
12. Declare a class to represent bank account of 10 customers with the following data members. Name of the depositor, Account number, Type of account (S for Savings and C for Current), Balance amount. The class also contains member functions to do the following: (i) To initialize data members (ii) To deposit money (iii) To withdraw money after checking the balance (minimum balance in Rs. 1000) (iv) To display the data members
13. Define a class worker with the following specification: Private members of class worker
wname 25 characters
hrwrk float (hors worked and wagerate per hour)
totwage float(hrwrk*wgrate)
calcwg A fuction to find hrerk* wgrate with float return type
Public members of class worker
in_data() a function to accept values for wno, wname, hrwrk, wgrate and invoke calcwg() to calculate totwage.
out_data() a function to display all the data members on the screen
14. Define a class Teacher with the following specification: private members:
name 20 characters
subject 10 characters
Basic,DA,HRA float
salary float
Calculate() function computes the salary and returns it. Salary is sum of Basic, DA and HRA
public members:
Readdata() function accepts the data values and invoke the calculate function
Displaydata() function prints the data on the screen.
Study Material - CS-XII Chap - 4 : Classes and Objects 15
Study Material - CS-XII Chap - 4 : Classes and Objects 15
15. Define a class Student with the following specification: private members:
roll_no integer
name 20 characters
class 8 characters
marks[5] integer
percentage float
Calculate() function that calculates overall percentage of marks and returns the percentage of marks.
public members:
Readmarks() a function that reads marks and invokes the calculate function.
Displaymarks() a function that prints the marks.
16. Write a program that invokes a function newdate() to return a object of date type. The function newdate() takes two parameters: an object olddate of date type and number of days (int) to calculate the newdate as olddate + number of days and returns the newdate.
Study Material - CS-XII Chap - 5 : Constructors & Destructors 1
CHAPTER - 5 : Constructors And Destructors
Constructors:
Constructors are member functions of a class which are used to initialize the
data members of the class objects. These functions are automatically called when an object of its class is created. There is no need to call these functions.
Characteristics of Constructors:
The name of a constructor is same as that of class in which it is declared. Constructors do not have any return type, not even void. Constructors are always defined in the public section of the class. They cannot be inherited, though a derived class can call the base class
constructor. Like other C++ functions, constructors can also be overloaded.
Types of Constructors: There are three types of constructors.
Default Constructors A constructor that accepts no parameter is called the default constructors.
Example class stud { int sno;
char sname[40]; public :
stud( ) // Default Constructor {
sno=0; strcpy(sname,“new” );
} void getinfo( ) {cin>> sno;
gets(sname);
} void showinfo( ) {cout<< sno; puts(sname); }
};
BY: MOHIT TANDON PGT(CS) LPS SEC-D
Study Material - CS-XII Chap - 5 : Constructors & Destructors 2
Study Material - CS-XII Chap - 5 : Constructors & Destructors 2
The above class stud has sno and sname as data members and three member functions i.e. stud (), getinfo(), showinfo( )
Here stud ( ) is a default constructor since having the same name as that of class and does not accepts any argument, also declared in the pubic section.
As we declare the object of this class it will immediately call to the constructor of the class.It automatically assigns the value 0 to variable sno and a “new” to sname. Here consider the following main function void main() {
stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values
} The default constructors are very useful when we want to create objects without having to type the initial values. With a default constructor objects are created just the same way as variables of other data types are created.
Parameterized Constructors A constructor that accepts parameters for its invocation is known as parameterized constructors. Example class stud {
Int sno; char sname[40]; public :
stud(int s, char n[ ] ) {
// Paramerized Constructor
sno=s; strcpy(sname,n);
} void getinfo( ) { cin>> sno;
gets(sname); } void showinfo( ) { cout<< sno;
puts(sname); }
}; This means we always specify the arguments whenever we declare an instance (object) of the class.
Study Material - CS-XII Chap - 5 : Constructors & Destructors 3
Study Material - CS-XII Chap - 5 : Constructors & Destructors 3
void main() {
stud obj (1, “Ashu”); // Parameterized constructor invoked Obj.showinfo(); // displays the value of sno as 1 and sname as “Ashu” Obj.getinfo(); // reads the user given value from the user Obj.showinfo(); // displays the user given values
}
Just like any other function a parameterized constructor can also have default arguments
e.g. stud(int s=0, char n[ ]=“new\0” ) A constructor with default arguments is equivalent to a default constructor. A class must not have a default arguments constructor and default constructor
together as it generates ambiguity.
Copy Constructors: A copy constructor is a constructor of the form classname( & classname). It is used to initialize an object with the values of another object.
The compiler will use the copy constructor whenever - 1. We initialize an instance using values of another instance of same type.
2. A function returns an object
3. A function receives an object as parameter. Example:
Study Material - CS-XII Chap - 5 : Constructors & Destructors 4
Study Material - CS-XII Chap - 5 : Constructors & Destructors 4
void main() {
stud obj; // Default constructor called Obj.showinfo(); // displays the value of sno as 0 and sname as “new” stud objnew(obj); // Copy constructor invoked and initialize the members
of object objnew with the values of object obj i.e. 0 and “new”.
Objnew.showinfo(); //displays the value of sno as 0 and sname as “new” Obj.getinfo(); //reads the user given value for object obj Obj.showinfo(); // displays the user given values for object obj Objnew.getinfo(); // reads the user given value for object objnew Objnew.showinfo(); // displays the user given values for object objnew
} Lets have a look:
Stud obj; // default constructor used
stud obj1(23, “Nisha”);// parameterized constructor used
stud obj2 = obj; // copy constructor used
stud obj3= obj1;// copy constructor used
Points to remember: Declaring a constructor with arguments hides the default constructor.
A Constructor with default arguments is equivalent to a default constructor.
A constructor declared under private access specifier, makes the class private and
object of a private class cannot be created.
A class must not have a default arguments constructor and default constructor
together as it generates ambiguity.
Constructors also show the polymorphism as a single class can have multiple
constructors of different forms. (Also known as constructor / function
overloading.)
Destructors: A destructor is a class member function that has the same name as the constructor (and the class ) but with a ~ (tilde) in front. e.g. ~stud() ; Destructor is used to deinitialize or destroy the class objects. When an object goes out of scope, its destructor is automatically invoked to destroy the object.
Example : #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h>
Study Material - CS-XII Chap - 5 : Constructors & Destructors 5
Study Material - CS-XII Chap - 5 : Constructors & Destructors 5
class stud { int sno;
char sname[40]; public :
stud( ) {
// Default Constructor
sno=0; strcpy(sname,"new"); cout<<"\nConstructing the object............";
} ~stud( )
{
// Destructor
cout<< "\nDestructing the object.............."; }
stud obj; // Default constructor called obj.showinfo(); // displays the value of sno as 0 and sname as “new” obj.getinfo(); // reads the user given value for object obj obj.showinfo(); // displays the user given values for object obj getch();
}
Output:
Study Material - CS-XII Chap - 5 : Constructors & Destructors 6
Study Material - CS-XII Chap - 5 : Constructors & Destructors 6
Study Material - CS-XII Chap - 5 : Constructors & Destructors 7
Study Material - CS-XII Chap - 5 : Constructors & Destructors 7
ASSIGNMENT Problem 1: Answer the questions (i) and (ii) after going through the following program:
{ Time=M.Duration; cout<<”Like Previous Match ”<<end1; }};
i. Which category of constructor - Function 4 belongs to and what is the purpose of using it?
ii. Write statements that would call the member Functions 1 and 3. Problem 2: What is the use of a constructor function in a class? Give a suitable
example of a constructor function in a class. Problem 3: What do you understand by default constructor and copy constructor
functions used in classes? How are these functions different form normal constructors?
Problem 4: Differentiate between default constructor and copy constructor, give
suitable examples of each. Problem 5: What is copy constructor? Give an example in C++ to illustrate copy constructor. Problem 6: Answer the questions (i) and (ii) after going through the following program:
#include <iostream.h> #include<string.h>
Study Material - CS-XII Chap - 5 : Constructors & Destructors 8
Study Material - CS-XII Chap - 5 : Constructors & Destructors 8
class Bazar { char Type[20]; char Product[20]; int Qty; float Price; Bazar( ) //Function 1
{strcpy (Type, “Electronic”); strcpy(Product, “Calculator”); Qty = 10; Price = 225; } public : void Disp( ) //Function 2 {cout << Type << “-“ << Product << “:” << Qty << ”@” << Price << endl; } }; void main( ) { Bazar B ; B. Disp( );
//Statement 1 //Statement 2
}
i. Will Statement 1 initialize all the data members for object B with the values given in the Function 1 ? (Yes OR No). Justify your answer suggesting the correction(s) to be made in the above code.(Hint: Based on the characteristics of Constructor declaration) ii. What shall be the possible output when the program gets executed? (Assuming, if required the suggested correction(s) are made in the program).
Problem 7: Answer the questions (a) and (b) after going through the following class:
class Interview { int month: public: Interview(int y) { Month=y;} Interview(Interview & t); };
1. Create an object, such that it invokes Constructor 1. 2. Write complete definition for Constructor 2.
Problem 8: Answer the questions (i) and (ii) after going through the following program:
class Match { int Time; public:
Match() //Function 1
Study Material - CS-XII Chap - 5 : Constructors & Destructors 9
Study Material - CS-XII Chap - 5 : Constructors & Destructors 9
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 15 of 38
Exercises: Now solve the following questions for practice
Q1.Write a program to store 5 records of student in the binary file “student.dat” where each student is
represented by following structure.
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Q2.Write a program to read the binary file “student.dat” and count the number of students scoring above
90% ,where each student is represented by following structure.
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Q3.Write a program to read the binary file “student.dat” and copy the information students to a new file
“alpha.dat” where percentage if below 33%. Each student is represented by following structure
struct student
{
int rn; //rollnumber
char name[80];
float per; //percentage
};
Appending data to a binary file:
struct Person{
char name[50];
int age;
char gender[10];
};
void main(){
Person P = {"SAM", 18, "male"};
ofstream outfile;
outfile.open("PERSON.dat", ios::binary | ios::app);//it opens a file and put the writing
//pointer at end of file
outfile.write((char *)&P, sizeof(P)); //it will write 62 bytes of person P data at end of file
outfile.close();
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 16 of 38
Searching in a Binary File
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
int main()
{
Student s2;
ifstream ip_file;
ip_file.open("File1.dat", ios::binary|ios::in);
int no;
cout<<"\nEnter roll no for Searching: ";
cin>>no;
int flag=0;
while(ip_file.read((char *)&s2, sizeof(s2)))
{
if(no==s2.roll)
{
flag=1;
break;
}
}
if(flag==1)
cout<<"\nRoll found.";
else
cout<<"\nRoll Not found!";
ip_file.close();
}
Insert a record at a certain position in a binary file: The process requires reading data from source file and copying data to a temporary data file along
with new data to be inserted.
Temporary file contains the updated data
Delete the source file and rename the temporary as source file.
step1 : create the input stream object and two record objects
student obj1,obj2={11,”anand”};
ifstream fin;
step 2:open the file by using stream object
fin.open(“file.dat”,ios::binary|ios::in);
step 3: create an output stream object and open the file “temp.dat”
ofstream fout;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 17 of 38
fout.open(“temp.dat”,ios::binary|ios::ios::out);// to hold the updated data
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==3)// inserting at 3
{
fout.write((char*)&obj2,sizeof(obj2));//insert before roll no 3 by copying it before 3 to
temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record obj1 after obj2
}
fout.write((char*)&obj1,sizeof(obj1));//copying current record obj1
}
Step 5: Close both the files
fin.close( );
fout.close( );
Step 6: Delete the original file “file.dat”
remove(“file.dat”); //statement to remove a file
Step 7: Rename the “temp.dat” to “file.dat” as temp.dat stores is the updated file
rename(“temp.dat”,”file.dat”); //statement to rename a file
Program for insertion of record at a certain place
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
void main( )
{
Student obj1,obj2={11,”anand”};
ifstream fin;
fin.open(“file.dat”,ios::binary|ios::in);
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==3)
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 18 of 38
{
fout.write((char*)&obj2,sizeof(obj2));//insert before roll no 3 by copying it before 3 to temp.dat
}
fout.write((char*)&obj1,sizeof(obj1)); //copying current record obj1 to temp.dat
}
fin.close( );
fout.close( );
remove(“file.dat”); //statement to remove a file
rename(“temp.dat”,”file.dat”); //statement to rename a file
}
Delete a record from a binary file The process requires reading data from source file and copying all the record to a temporary data
except the record to be deleted.
Temporary file contains the updated data
Delete the source file and rename the temporary as source file.
step1 : create the input stream object and a record object
student obj1;
ifstream fin;
step 2:open the file by using object
fin.open(“file.dat”,ios::binary|ios::in);
step 3: create an output stream object and open the “temp.dat” file
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn!=11) // delete roll no 11 by not copying to temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record except 11 roll no
}
Step 5: Close both the files
fin.close( );
fout.close( );
Step 6: Delete the original file “file.dat”
remove(“file.dat”);//statement to remove a file
Step 7: Rename the “temp.dat” to “file.dat” as temp.dat stores is the updated file
rename(“temp.dat”,”file.dat”);//statement to rename a file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 19 of 38
Program for deletion of a record
#include<fstream.h>
struct Student
{
int roll;
char name[80];
};
void main( )
{
student obj1,obj2={11,”anand”};
ifstream fin;
fin.open(“file.dat”,ios::binary|ios::in);
ofstream fout;
fout.open(“temp.dat”,ios::binary|ios::ios::out);
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn!=11) // delete roll no 11 by not copying to temp.dat
fout.write((char*)&obj1,sizeof(obj1));//copying current record except 11 roll no
}
fin.close( );
fout.close( );
remove(“file.dat”);//statement to remove a file
rename(“temp.dat”,”file.dat”);//statement to rename a file
}
Random file access functions and file pointers:
Each stream has internally two pointers to represent the reading and writing location.
These are said as get pointer and put pointer.
write( ): it writes the record and moves the position of put pointer forward by one record.
read( ): it reads the record and moves the get pointer forward one record by one record.
To manipulate position of get pointer and pointer following functions are used:
seekg( ): it is used to change position of get pointer i.e forward or backward before reading data
randomly from any location in a file.it is used with ifstream and fstream
seekp( ): it is used to change position of put pointer i.e forward or backward before writing data
randomly from any location in a file. it is used with ofstream and fstream
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 20 of 38
Unserstanding seekg( ) and seekp( ):
Syntax:
Stream_object.seekg(offset,refposition);
Stream_object.seekg(offset); //refposition will be set from beginning of file
Stream_object.seekp(offset,refposition);
Stream_object.seekp(offset); //refposition will be set from beginning of file
Here offset is distance in bytes( it is in long integer in turbo c++) from refposition.
refpoistion: it represents the start point of changing position of file pointer
refposition is represented by following constants:
ios::beg – refposition will be from start of file.( default type)
ios::cur – refposition will be from current position of get pointer.
ios::end – refposition will be from end of file
Example: To change position of get pointer using seekg ()
struct student
{
int rn;
char name[80];
};
void main()
{
ifstream Fin;
Fin.seekg(0); // it will move the position to beginning of file
Fin.seekg(sizeof(student)*5,ios::beg);//it will reposition get pointer to the end of 5th
record or
//beginning of 6th
record
Fin.seekg(-5*sizeof(student),ios::end);//it will reposition get pointer to 5 record back from end of file
Fin.seekg(0); //it takes get pointer to the end of file
Fin.seekg(-1L*sizeof(student),ios::cur); //takes to beginning of current record(82 bytes back)
}
Example: To change position of get pointer using seekp ()
struct student
{
int rn;
char name[80];
};
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 21 of 38
void main()
{
ofstream File;
File.seekp(0);// it will move the position to beginning of file
File.seekp(sizeof(student)*5,ios::beg);//it will reposition get pointer to the end of 5th
record or
//beginning of 6th
record
File.seekp(-5*sizeof(student),ios::end);//it will reposition get pointer to 5 record back from end of file
File.seekp(0,ios::end); //it takes get pointer to the end of file
File.seekp(-1L*sizeof(student),ios::cur); //takes to beginning of current record(82 bytes back)
}
Knowing the position of get pointer:
tellg( ): it returns the location of get pointer in bytes(integer).It is used with respect to input stream.
Syntax:
streamObject.tellg( )
ifstream File;
File.seekg(0); // it will move the position to beginning of file
int pos=File.tellg( ); // pos will store 0
Knowing the position of put pointer:
tellp( ): //it returns the location of put pointer in bytes(integer)
ofstream File;
File.seekp(0); // it will move the position to beginning of file
int pos=File.tellp( ); // pos will store 0
Exercises:
Q1.A binary file stores records of 100 students where each student have following structure:
struct student
{
int rn;
char name[80];
};
i) Now give the output of following statements:
Student T;
ifstream fin;
Fin.open(“student.dat”,ios::binary | ios::in);
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 22 of 38
Fin.read((char*)&T,sizeof(T));
Fin.read((char*)&T,sizeof(T));
cout<<fin.tellg( )<<endl;
Fin.seekg(12*sizeof(T));
cout<<Fin.tellg()<<endl;
Fin.seekg(-5L*sizeof(T),ios::cur);
cout<<Fin.tellg( );
Fin.seekg(0,ios::end);
cout<<fin.tellg()/(sizeof(T)*2);
ii) Now give the output of following statements:
Student T={2”aman”};
ofstream fin;
Fin.open(“student.dat”,ios::binary | ios::out);
Fin.write((char*)&T,sizeof(T));
Fin.write((char*)&T,sizeof(T));
cout<<fin.tellp( )<<endl;
Fin.seekp(6*sizeof(T),ios::beg);
cout<<Fin.tellp()<<endl;
Fin.seekp(-1L*sizeof(T),ios::cur);
cout<<Fin.tellp( );
Fin.seekp(0,ios::end);
cout<<Fin.tellp()/sizeof(T);
Fin.seekp(0);
cout<<Fin.tellp();
Modification of record in a binary file.
fstream : fstream class provides reading and writing operation simultaneously so modification of records
is done through fstream class.
Steps involved:
step1 : create the fstream stream object
fstream fin;
step 2:open the file by using object
fin.open(“file.dat”,ios::binary|ios::in|ios::out);// open file in input and output modes
step 3: create object of given structure to hold record
student obj1;// holding record of data file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 23 of 38
step 4:read the record one by one from “file.dat”
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==11) // modify record having roll no 11
{ //if found move to the beginning of current record
Fin.seekg(-1L*sizeof(obj1),ios::cur);
//modify the record
Obj1.rn=111;
strcpy(obj1.name,”mohan”);
//rewriting record to binary file
fout.write((char*)&obj1,sizeof(obj1)); //it will modify the record
}
Step 5: Close both the files
fin.close( );
fout.close( );
Complete program of above steps for record modification:
#include<fstream.h>
#include<string.h>
struct student
{
int rn;
char name[80];
};
void main()
{
fstream fin;
fin.open(“file.dat”,ios::binary|ios::in|ios::out); // open file in input and output modes
student obj1; // holding record of data file
while(fin.read((char*)&obj1,sizeof(obj1)))
{
if(obj.rn==11) // modify record having roll no 11
{ //if found move to the beginning of current record
Fin.seekg(-1L*sizeof(obj1),ios::cur); //L is long integer
obj1.rn=111; //modify the record
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 24 of 38
strcpy(obj1.name,”mohan”);
//rewriting record to binary file
fout.write((char*)&obj1,sizeof(obj1));//it will modify the record
}
fin.close( );
fout.close( );
}
Exercise:
Q1.Write a program to create a binary file “scholar.dat” and store 5 records of scholar
And carry out following file operation using a menu bases options
Define a function to append a scholar at the end of file
Define a function to accept any name and search it if found display its information
Define a function to accept a scholar and a name , search the name if found insert the scholar after
that record
Define a function to accept a name and delete the scholar having that name
Define a function to increase the scholar per% by 5 where per% is between 28 to 32.
Define a function to display all the scholar information on screen
READING AND WRITING CLASS OBJECTS
Like structure object read( ) and write ( ) are used to read and write class objects as a single unit.
Only data members are written to disk not the member functions.
Example:
#include<fstream.h>
#include<stdio.h>
class doctor
{
int doc_id;
char dname[80];
float salary;
public:
void enter()
{
cin>>doc_id;
gets(dname);
cin>>salary;
}
void disp()
{
cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl;
}
};
void WRITE( )//function to write data to “doctor.dat” file
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 25 of 38
{
Doctor obj;
Ofstream T;
T.open(“doctor.dat”,ios::binary|ios::out);
for(int i=1;i<=4;i++)//
{
obj.enter( ); //calling public member function to initialize private data members
T.write((char*)&obj,sizeof(obj)); //write record containing through obj object
}
T.close();
}
void APP( ) // to add record at end of file
{
Doctor obj;
Ofstream T;
T.open(“doctor.dat”,ios::binary|ios::app);
obj.enter();
T.write((char*)&obj,sizeof(obj));
T.close( );
}
void READ( )
{ Doctor obj;
ifstream T;
T.open(“doctor.dat”,ios::binary|ios::in);
while(T.read((char*)&obj,sizeof(obj)))//loop breaks if no valid data left i.e T becomes null
{
obj.disp();//calling public member function to display private data members
}
T.close();
}
void main( )
{WRITE( ); //calling function to write data
READ( ); // calling function to read and display data on screen
APP( ); //calling function to add a record at end of file
}
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 26 of 38
Chapter 7 : Data File Handling
ASSIGNMENTS
Q1 Name the header file required to carry out data file operations.
Q2 Explain the difference between binary file and text file.
Q3 Give difference between : I. ios::in and ios::out
II. ios::app and ios::ate
Q4 Give difference between get( ) and getline( ).
Q5 Give difference between seekg( ) and tellg( ).
Q6 Write statements at the given places for pre-existing binary file ”abc.dat” that stores records of items as per following information in the . struct item { int code; char name[80]; }; fstream FIT; __________________________//to open the file in I/O mode __________________________//to move to beginning of 2nd last record _____________________________// to move to beginning of file _______________________________//to display the byte number
Q7 Define a function to create a text file “os.txt” and store name of 6 operating systems in it.
Q8 Define a function to add two more operating system names in “os.txt”.
Q9 Define a function read “os.txt” file and return the number of operating systems that starts with “win”.
Q10 Define a function read “os.txt” file and return the number of upper case vowels.
Q11 Define a function read “os.txt” file and return the number of words having odd number of characters
Q12 Define a function read “os.txt” file and return the number of lines that starts with letter ‘A’.
Q13 Define a function read “os.txt” file and print the average length of line.
Q14 Define a function read “os.txt” file and print the word with maximum number of characters.
Q15 Define a function read “os.txt” file and copy all upper case alphabets to “upper.txt” and all lower case letters to “lower.txt”
Q16 Define a function create a binary file “doc.dat”and store 5 records where each record is having following structure: class doctor { int doc_id; char dname[80]; float salary; public:
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
Q17 Define a function open binary file “doc.dat” and append 2 records where each record is having following structure: class doctor { int doc_id; char dname[80]; long salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q18 Define a function read the binary file “doc.dat” and count the doctors where salary is in the range 120000-300000 and where each doctor is defined by the following class. class doctor { int doc_id; char dname[80]; long salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } long rt_sal(){return salary;} void disp()
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
Q19 Define a function to read the binary file “doc.dat” copy all the doctors to file “elite.dat” where specialisation is in “radiologist”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } int check(char a[]) { return strcmpi(a,spl); } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q20 Define a function open the binary file “doc.dat” and delete information of those doctors where specialisation is either “neuro” or “gastro”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } char *rt_name() { return name;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
Q21 Define a function open the binary file “doc.dat” and insert a new doctor information at 3rd place from beginning. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } void disp() { cout<<doc_id<<”\t”<<dname<<”\t”<<salary<<endl; } };
Q22 Define a function open the binary file “doc.dat” increase the salary of those doctors by 20% where specialisation is “neuro”. class doctor { int doc_id; char dname[80]; char spl[80]; //type of specialisation float salary; public: void enter() { cin>>doc_id; gets(dname); cin>>salary; } char *rt_name() { return name; } void setsal(long p)
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
Q23 Observe the program segment carefully and answer the question that follows: class item { int item_no; char item_name[20]; public: void enterDetail( ); void showDetail( ); int getItem_no( ){ return item_no;} }; void modify(item x, int y ) { fstream File; File.open( “item.dat”, ios::binary | ios::in | ios::out) ; item i; int recordsRead = 0, found = 0; while(!found && File.read((char*) &i , sizeof (i))) { recordsRead++; if(i . getItem_no( ) = = y ) { _________________________//Missing statement File.write((char*) &x , sizeof (x)); found = 1; } } if(! found) cout<<”Record for modification does not exist” ; File.close() ; } If the function modify( ) is supposed to modify a record in the file “ item.dat “, which item_no is y, with the values of item x passed as argument, write the appropriate statement for the missing statement using seekp( ) or seekg( ), whichever is needed, in the above code that would write the modified record at its proper place.
Q24 Observe the program segment carefully and answer the question that follows: class item
{ int item_no;
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
If the function modify( ) modifies a record in the file “ item.dat “ with the values of item x passed as argument, write the appropriate parameter for the missing parameter in the above code, so as to modify record at its proper place.
Q25 Observe the program segment given below carefully and fill the blanks marked as Line 1 and Line 2 using fstream functions for performing the required task. #include<fstream.h> class Stock { long Ino; // Item Number char Item[20]; // Item Name int Qty; // Quantity public: void Get(int); Get(int);// Function to enter the content void Show( ); // Function to display the content void Purchase(int Tqty) { Qty+ = Tqty; // Function to increment in Qty } long KnowIno( ) { return Ino; } };
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 32 of 38
void Purchaseitem(long PINo, int PQty) // PINo -> Info of the item purchased // PQty -> Number of items purchased { fstream file; File.open(“ITEMS.DAT”,ios::binary|ios::in|ios::cut); int Pos=-1; Stock S; while (Pos== -1 && File.read((char*)&S, sizeof(S))) if (S.KnowInc( ) == PINo) { S.Purchase(PQty); // To update the number of items Pos = File.tellg()- sizeof(S); //Line 1 : To place the file pointer to the required position ______________________________________; //Line 2 : To write the objects on the binary file ______________________________________; } if (Pos == -1) cout<<“No updation done as required Ino not found...”; File.close( ); }
Q26 Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg( ), seekp( ), tellp( ) and tellg() functions for performing the required task. # include <fstream.h> class PRODUCT { int Pno; char pname [20]; int qty; public : void ModifyQty();// The function is to modify quantity of a PRODUCT }; void PRODUCT :: ModifyQty ( ) { fstream Fil; Fil.open(“PRODUCT.DAT”,ios::binary | ios::in | ios::out); int MPno; cout<<“Product No to modify quantity :”; cin>>MPno; while( Fil.read ((char*) this, sizeof (PRODUCT))) { if (MPno ==Pno) {
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 33 of 38
cout<<“present quantity:” <<Qty<<endl; cout<<“changed quantity:”; cin>>Qty; int position = ________; //Statement 1 ___________________; //Statement 2 Fil.write ((char*) this, sizeof (PRODUCT)); // Re-writing the Record } } Fil.close( );}
Q27 Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg() and tellg() functions for performing the required task. #include <fstream.h> class Employee { int Eno; char Ename[20]; public: //Function to count the total number of records int Countrec(); }; int Item::Countrec() { fstream File; File.open(“EMP.DAT”,ios::binary|ios::in); ______________________ //Statement 1 int Bytes = ______________________ //Statement 2 int Count = Bytes; sizeof(Item); File.close(); return Count; }
Q28 Write a function in C++ to count the no. of “Me” or “My” words present in a text file “DIARY.TXT”. If the file “DIARY.TXT” content is as follows : My first book was Me and My family. It gave me chance to be known to the world. The output of the function should be Count of Me/ My in file :3
Q29 Assuming the class EMPLOYEE given below, write functions in C++ to perform following: (i) Write the objects of EMPLOYEE to a binary file. (ii) Read the objects of EMPLOYEE from binary file and display them on screen. class EMPLOYEE { int ENO; char ENAME[10]; public :
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
Q30 Consider the class declaration: class BUS { int bus_no; char destination[20]; float distance; public : void Read(); // To read an object from the keyboard void Write (); // To write an object into a file void Show (); // To display the file contents on The monitor }; Complete the member functions definitions.
Q31 Write a function in C++ to search for a laptop from a binary file “LAPTOP.DAT” containing the objects of class LAPTOP (as defined below). The user should enter the Model No and the function should search and display the details of the laptop. class LAPTOP { long ModelNo; float RAM, HDD; char Details[120]; public: void StockEnter ( ) { cin>>Model>>No>>RAM>>HDD; gets(Details); } void StockDisplay( ) {cout<<ModelNo<<RAM<<HDD<<Details<<endl; } long ReturnModelNo ( ) { return ModelNo ; } };
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 35 of 38
Q32 Write a function in C++ to search and display the details of all flights, whose destination is “Mumbai” from “FLIGHT.DAT”. Assuming the binary file is containing objects of class FLIGHT. class FLIGHT { int Fno; //Flight Number char From[20] ; //Flight Starting point char To[20] ; //Flight Destination public : char* GetFrom( ) { return From ; } char* GetTo( ) { return To ; } void Enter( ) { cin >> Fno ; gets (From) ; gets(To) ; } void Display( ) { cout << Fno<< “:” << From << “:” << To << endl ; } };
Q33 A binary file “Students.dat” contains data of 10 students where each student’s data is an object of the following class:
class Student { int Rno;char Name[20]; public: void EnterData() {cin>>Rno; cin.getline(Name,20); void ShowData() {cout<<Rno<<” - ”<<Name<<endl;} };
With reference to this information, write output of the following program segment: ifstream File; Student S; File.open(“STUDENTS.DAT”,ios::binary|ios::in); File.seekg(0, ios::end);
cout<<File.tellg();
Q34 Assuming the class Account given below and a binary file BANK.DAT contains objects of this class, write functions in C++ to perform the followings:
(i) Deposit ( ), which deposits amount x to account number y. (ii) Withdraw ( ), which withdraws amount x from account number y.
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 36 of 38
class Account{ int acc_no; char name[20]; float balance; public: float getBalance( ) { return balance; } void setBalance(float f ) { balance = f; } int get_acc_no( ) { return acc_no; } };
Multiple choice based
Q1 What enables a program to store the data permanently on secondary storage devices? (a) monitor (b) printer (c) file (d ) None of these
Q2 A collection of related data stored on some storage devices such as a hard disk, magnetic tape or floppy disk. (a) program (b) process (c) file (d ) None of these
Q3 Data files can be classified as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q4 The files that store data in the form of machine form are known as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q5 The files that store data as strings of characters are known as (a) Text File (b) Binary File (c) Both (a) & (b) (d ) None of these
Q6 A flow of data in the form of a sequence of bytes is known as____ (a) word (b) string (c) stream (d ) None of these
Q7 The stream that reads the data from the device and supplies it to the program is known as (a) input stream (b) output stream (c) Both (a) & (b) (d ) None of these
Q8 The stream that receives data from the program and writes it to the device is known as
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 37 of 38
(a) input stream (b) output stream (c) Both (a) & (b) (d ) None of these
Q9 Which one is file input stream class ? (a) ifstream (b) ofstream (c) both (a) & (b) (d ) None of these
Q10 Which one is file output stream class (a) ifstream (b) ofstream (c) both (a) & (b) (d ) None of these
Q11 Which is both file input and output stream class (a) ifstream (b) ofstream (c) fstream (d ) None of these
Q12 A file can be opened by (a) constructor (b) open( ) (c) both (a) & (b) (d ) None of these
Q13 Two or more file modes can be combined using the operator (a) bitwise OR (|) (b) bitwise AND ( &) (c) both (a) & (b) (d ) None of these
Q14 The default mode for the ifstream class is (a) ios::in (b) ios::out (c) both (a) & (b) (d ) None of these
Q15 The default mode for the ifstream class is (a) ios::in (b) ios::out (c) both (a) & (b) (d ) None of these
Q16 By default all files are open in which mode (a) text mode (b) binary (c) both (a) & (b) (d ) None of these
Q17 The open in which mode is compulsory to close the file by close( ) method (a) constructor (b) open( ) (c) both (a) & (b) (d ) None of these
Q18 Which method is used to read the data from a file (a) get( ) (b) read( ) (c) both (a) & (b) (d ) None of these
Q19 Which method is used to write the data to the file (a) put( ) (b) write( ) (c) both (a) & (b) (d ) None of these
Q20 The current position of a get pointer can be known by using (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q21 The current position of a put pointer can be known by using (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q22 Which of these stream classes can be used to read data from a file? (a) fstream (b) ifstream ( c) ofstream (d ) both (a) & (b)
Q23 Which of these file modes allows to write data anywhere in a file? (a) ios::ate (b) ios::app
XII/CS(283)/NOTES GAJENDRA S DHAMI,PGT(CS) ,LUCKNOW PUBLIC SCHOOL,SOUTH-CITY
CHAPTER 7:DATA FILE HANDLING Page 38 of 38
(c) ios::out (d ) ios::trunc
Q24 Which of these functions allows to change the position of the get pointer? (a) tellg( ) (b) tellp( ) (c) seekg( ) (d ) seekp( )
Q25 Which of these refers to the end position of a file? (a) ios::beg (b) ios::end (c) ios::cur (d ) None of these
Q26 Which of these functions returns a non-zero value if end of file is encountered while reading data from a file ? (a) eof( ) (b) fail( ) (c) bad( ) (d ) good( )