OOP Lab Manual (1)
OOP Lab Manual (1)
PUNE
DEPARTMENT OF AI & DS ENGINEERING
Lab Manual
SE - SEM 1
LAB TEACHER
PROF. ASHVINI SWAMI
Object Oriented
Programming
Laboratory Manual
Table of Contents
Group C
Sessions
6. Write C++ program using STL for Sorting and searching with
user- defined records such as Person Record (Name, birth date,
telephone no), item record (item code, item name, quantity and
cost)
7. Write a program in C++ to use map associative container. The
keys will be the names of states and the values will be the
populations of the states. When the program runs, the user is
prompted to type the name of a state. The program then looks
in the map, using the state name as an index and returns the
population of the state.
Faulty In Charge
Prof. Ashvini Swami
Vision
1. To be the competitive and renowned technical institute imparting quality education for socio-
economic development of our country.
Mission
1. To prepare well cultured and knowledgeable technocrats by imparting quality education.
Experiment No.: Group A - 01
Title: Implement a class complex which represent the Complex Number datatype. Implement the
following operations:
Aim: To implement a class complex which represent the Complex Number datatype.
Theory:
Concept of overloading :
There are two ways of overloading that are operator overloading & function overloading. Here in
thisprogram, we use operator overloading.
Operator overloading-
1. Operator overloading can be defined a new meaning for an existing "operator". There are many
operator which can be overloaded such as mathematical operator, logical operator, relational
operator etc.
a) . And*
b) size of
c) :: (scope resolution)
3. C++ provide the flexibility to the programmers in extending these build-in operators.
Need of operator overloading-
There are predefined operators such as +, -, * , / & so on which operates on fundamental data types
such as integer , double , char and so on. In order to make user defined data type as natural as
fundamental datatype, the user defined datatype can be associate with the set of predefined operators
the concept called operator over loading is used.
Note that the fundamental meaning of these operators is not at all changed by operator overloading.
Rather; with this meaning these operators are associated with the user defined data type. Rules for
operator overloading –
1. The basic meaning of operator cannot be changed.
3. Binary operator overloaded through member function must take one explicit argument.
Conclusion:
By doing above program I conclude that operators can be overloaded to do the operations on objects
ofclass complex.
Experiment No.: Group A - 02
Title:
Develop an object oriented program in C++ to create a database of student information system
containing the following information: Name, Roll number, Class, Division, Date of Birth, Blood
group, Contact address, Telephone number, Driving license no. etc Construct the database with
suitable member functions for initializing and destroying the data viz Constructor, Default
constructor, Copy constructor, Destructor, Static member functions, friend class, this pointer, inline
code and dynamic memory allocation operators-new and delete as well as Exception Handling.
Aim:
To use object oriented concepts for implementation of student database.
Theory:
Constructor:
It is special member function who set ask to initialize of object of its class. Its name is same as class
name & the constructor is invoked whenever an object of its associated class is created. It does not
have any return type. It is called constructor because it construct the values ofdata member of the
class.
Default constructor:
When no arguments will be passed through the constructor, it becomes a Default constructor. This
is used to create objects & initialize them.
Copy constructor: A constructor can accept a reference to its own class as a parameter. Thus, the
statement
Class shape
{
public:
shape(shape&);
};
In such cases, the constructor is called the copy constructor. A copy constructor is used todeclare &
initialize an object from another object.
Destructor:
Destructor is a special member function of class i. e. executed whenever object of
This class goes out of the scope or delete expression in that apply to the pointer of object of this
class. It uses tilde operator (~).
A destructor never takes any arguments nor does it return any value.
Static Member Functions:
A member function that is declared static has the following properties:
1. A static function can have access to only static members (functions or variables) declared in the
same class.
2. A static member function can be called using the class name (instead of its objects) as follows:
Friend Class:
A class can have friendship with another class, if there are two classes first & second. If firstclass
grants friendship with other class second then the private data member of the class first are
permitted to be access by the public member of the class second but on other hand public member of
class first can not access the private member of the class second.
This pointer:
This is pointer that points to the object for which this function was called. This unique pointer is
automatically passed to a member function when it is called. The pointer this acts as an implicit
argument to all the member function.
class ABC
{
int a ;
};
C++ uses a unique keyword called this to represent an object that invokes a member function this is
a pointer that points to the objects for which this function was called. For example, the function call,
A max () will set the pointer this to the address of the object A. The starting address is the same as
the address of the first variable in the class structure.
This unique pointer is automatically passed to a member function when it is called. The pointer this
acts as an implicit argument to all the member functions . Consider the following simple example:
class ABC
{
int a;
.................
..................
};
The private variable 'a' can be used directly inside a member function, like a=123;
We can also use the following statement to do the same job: this-> a=123;
Since C++ permits the use of shorthand form a =123, we have been using the pointer this explicitly
so far. However, we have been implicitly using this pointer this when overloading the operators
using member function.
Inline code:
C++ has a different solution to this problem. To eliminate the cost of calls to small functions, C++
proposes a new feature called in line function an inline function is a function that isexpanded in line
when it is invoked. That is, the compiler replaces the function call with the corresponding function
code.
e.g.
function body;
Conclusion:
By executing this program, I understand the concepts of constructor, destructor, new, delete, inline
function, static function, static variables, copy constructors etc.
Experiment No.: Group A - 03
Title:
Imagine a publishing company which does marketing for book and audio cassette versions. Create a
classpublication that stores the title (a string) and price (type float) of a publication. From this class
derive two classes: book, which adds a page count (type int), and tape, which adds a playing time in
minutes (type float).
Write a program that instant a test he book and tape classes, allows user to enter data and displays
thedata members. If an exception is caught, replace all the data member values with zero values.
Aim:
To implement a class which stores the title and price of book and its two derived classes to store
pagecount and play time also to handle exception when zero value for data member occurs.
Theory:
Inheritance:
The class from which the data members and member functions used by another class iscalledthe
baseclass.
The class which uses the properties of base class and at the same time can add its own properties is
called derived class.
There are three types of access specifier or qualifier using which the members of the class are
accessed by theother class –
The derived class can inherit baseclass publicly or privately.The notation used for inheritance is: For
ex:
classderived_class_name:access_specifierbase_class_name
The first line indicates that there are two classes d1 and b1.It means“the derived class d1 inheritsthe
base class b1 publicly” .
The second line indicates that there are two classes d2 and b2.It means“the derived class d2 inherits
the base class b2 privately” .
The base class and derived class can generate their own objects.These objects differ from each other.
Relation between Base class and Derived class:
Inheritanceisanimportantfeatureinobjectorientedprogrammingthatallowsthereusabilityofthe code.
The fundamental idea behind the inheritance is that – make use of data members and member
functions of base class in derived class along with some additional fundamentalism present in
derivedclass.
When we create an object for derived class then first of all the Base class constructor is called and
after that the derived class constructor is called.
The reason behind this is that is that the Derived class inherits from the Base class,both the Base
classand Derived class constructors will be called when a Derived class object is created.
Exception Handling:
The errors that are caused by events beyond the control of the program (such as keyboard interrupts
) are called asynchronous exception.The proposed exception handling mechanics min c++ is
designed to handle only synchronousexception.
Exception Handling mechanism
C++ exception handling mechanism is basically built upon three keywords namely,try,throw and
catch.
The keyword try is used to preface a block of statements surrounded by braces which may generate
exceptions. Theseblock of statements are known as try block. When expression is detected it is
known as throw statement.
A handler may decide to throw the exception caught without processing it.In such situations,we may
simply invoke throwwithout any argument as shown below:
Throw;
This causes the current exception to be thrown to then exten closing try / catch sequence and is
caught by a catchstatement listed after that enclosing try block.
Conclusion:
From this program we can conclude that by using inheritance and exception handling we can reduce
the efforts in writingthe code. Inheritance helps us to use a particular member again without any
need of writing it again while exception handling helps to detect the exceptions that occur during
runtime.
Experiment No.: Group B - 04
Title:
Write a C++ program that creates an output file, writes information to it, closes the file and open it
again as an input file and read the information from the file.
Aim:
To create an output file writes information to it closes the file and open it again as an input file and
readthe information from the file.
Theory:
The stream can represent file, console,block of memory or hardware device.the iostreaml ibrary
provides the common set of functions for handling these streams .
The file operations are associated with the object of the classes if stream,of stream or fstream.Hence
we need to create an object of corresponding classes .
The file can be opened by the function called open().The syntax of file openis
open(file_name,mode);
The file name is an ullterminated string that represents the name of the file that is to be open.wecan
use open() function using the given syntax as :
ofstreamobj ; obj.open("sample.dat",ios::out|ios::binary);
That means the file sample.dat is opened for output to operation in binary mode.Thus we can
combinethe flags using OR( | ) operator.
This is_open()is a boolean function that can be used to check whether the file is open not. for
example
if(obj.is_open())
To close the file the member function close()is used.The close function takes no parameter and
returns no value.
object.close();
You can detect when the end of an input file has been reached by using there o f()member function
ofios. It returns true when the end of the file has been encountered and false otherwise.
For finding end of the file we use of () function.This function is a member function of ios class.If
end offile I encountered then it return a non zero value.
UnformattedI/OFunctions:
The get and put functions are used to read and dis.play the contents. Thesyntax of get and put
function s i s
Get(char ch);
Put(char ch);
The get line function is used to read the file line by line and the write statement is used to write the
contents either to the file or to the console.
File pointers:
File pointers are used for locating the position in the file.With each file object the rear two pointers
associated with it. The get pointer and put pointer are the pointers basically return the current get
position and current put positions.
While performing file operations,we must be able to reach at any desired position inside the file.For
this purpose there are two commonly used functions-
Seek
Seekg means get pointer of specific location for reading the records. Seekp means get pointer of
specific location for writing the records. The syntax of seek is
Seek g(offset,reference-position); Seekp(offset,reference-position);
Where,off set is any constant specifying the location,reference position is for specifying
beginning,endof current position. It can be specified as:
Conclusion:
By executing above program I understand that how the file is created so as to store the contains of
anyobject permanently. It concludes that we can write the contains in the file and read that contains
whenever require
Experiment No.:Group B - 05
Title:
Write a function template for selection sort. Write a program that inputs, sorts and outputs an integer
array and float array.
Aim:
Theory:
Selection Sorting:
In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It
has O (n2) time complexity, making it inefficient on large lists, and generally performs worse than
the similarinsertion sort. Selection sort is noted for its simplicity, and it has performance advantages
over more complicated algorithms in certain situations, particularly where auxiliary memory is
limited.
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built
up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that
occupythe rest of the list. Initially, the sorted sublistis empty and the unsorted sublist is the entire
inputlist. Thealgorithm proceeds by finding the smallest (or largest, depending on sorting order)
element in the unsorted sublist,exchanging(swapping)it with the leftmost unsorted element(putting it
in sorted order), and moving the sublist boundaries one element to the right
Template:
Templates are the foundation of generic programming, which involves writing code in away that is
independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers
like iterators and algorithms are examples of generic programming and have been developed using
template concept.
There is a single definition of each container,such as vector,but we can define many different kinds
ofvectors for example, vector <int> or vector <string>.
You can use templest of define functions as well as classes,let us see how do they work: Function
Template:
The general form of a template function definition is shownhere: template<classtype>ret-typefunc-
name(parameterlist)
{
//body of function
Here, type is a placeholder name for a data type used by the function. This name can be used within
thefunction definition.
Class Template:
Just as we can define function templates, we can also define class templates. The general form of a
generic class declaration is shown here:
template<classtype>classclass-name
... . . . .. .
Here,type is the place holder type name,which will be specified when a class is instantiated.You can
define more than one generic data type by using a comma-separated list.
Conclusion:
Title:
Write a C++ Program using STL for sorting and searching user defined records such as personal
records(name, DOB, telephone number etc.) using vector container.
Aim:
Theory:
In more details it is implemented using hybrid of Quick Sort, Heap Sort and Insertion Sort.By
default, it uses Quick Sort butif Quick Sort is doing unfair partitioning and taking more than N*log
N time, it switches to Heap Sort and when the array size becomes really small, it switches to
Insertion Sort.
In more details it is implemented using hybrid of Quick Sort, Heap Sort and Insertion Sort.By
default, it uses Quick Sort butif Quick Sort is doing unfair partitioning and taking more than
N*logN time, it switches to Heap Sort and when the array size becomes really small, it switches to
Insertion Sort.
Functions :-
/*-------------<< Main Function Starts >> ------------ */
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class student
{
public:
int rollno; string name; char dob[15];
vector<student> read()
{
int n; student k;
vector<student> j;
cout<< "\nEnter total no. of students : ";cin>>n;
for(int i=0;i<n;i++)
{
cin>>k; j.push_back(k);
}
return j;
}
void delet(vector<student>&j)
{
student k;
cout<<"\nEnter Student Roll No To Delete : ";cin>>k.rollno;
vector<student>::iterator p;p=find(j.begin(),j.end(),k);
if(p!=j.end())
j.erase(p);
else
cout<<"\nNot found ";
}
/*-------<< FunctionDefination For Search Record >> */
void search( vector<student>&j )
{
student k;
cout<<"\nEnter Student Roll No To Search : ";
cin>>k.rollno;
cout<<"\n\n\t\tROLL NO\t\tNAME\t\tDATE OF BIRTH";
vector<student>::iterator p;
p=find(j.begin(),j.end(),k);
if(p!=j.end())
cout<<*p;
else
cout<<"\nNot found ";
}
/*-------<< FunctionDefination For Sort Record >> */
void sort( vector<student>&j)
{
sort(j.begin(),j.end(),myfunc);
}
cin>> op; switch(op)
{
case 1:
j=read();break;
case 2: print(j);break;
insert(j);break;
case 3:
delet(j);break;
case 4: search(j);break;
sort(j);
case 5:
case 6:
print(j);
break;
}
}while(op!=7);
}
Title:
Write a program in C++ to use map associative container. The keys will be the names of states and
the values will be the populations of the states. When the program runs, the user is prompted to type
the name of a state. The program then looksin the map, using the state name as an index and returns
the population of the state.
Aim:
Theory:
Maps are associative containers that store elements in a mapped fashion. Each element has a key
valueand a mapped value. No two mapped values can have the same key values.
syntax:
std::map<key_datatype, value_datatype>map_name;
map<string, int>my_map;
We declared a map named my_map. The map will have a string as key datatypes andinteger as
values datatype.
Member types:
The member functions can use the following members types as either parameters orreturn type:
5. value_type: pair<constkey_type,mapped_type>
7. reference: allocator_type::reference
8. const_reference: allocator_type::const_reference
9. pointer: allocator_type::pointer
□ begin()- This function returns the iterator to the first item of the map.
□ size()-This function returns the number of items in a map.
□ empty()-This function returns a Boolean value denoting whether a map isempty.
□ insert( pair(key, value))- This function inserts new key-value pair to a map.
□ find(val)- This function gives the iterator to the val element if it’s found.Otherwise, it will
return m.end().
□ Erase (iterator position)- This function deletes the item at the position pointedby the
iterator.
□ erase(const g)– This function deletes key-value g from a map.
□ Clear ()-This function deletes all items from a map.
You can iterate over the map elements. We simply need to create an iterator and use itfor this.
For example:
Example 1:
#include <iostream>#include <string> #include <map>
map<int, string>Students;
Students.insert(std::pair<int, string>(200, "Alice"));
Students.insert(std::pair<int, string>(201, "John"));
cout<< "Map size is: " <<Students.size() <<endl; cout<<endl<< "Default map Order is: "
<<endl;
for (map<int, string>::iterator it = Students.begin(); it != Students.end(); ++it)
{
cout<< (*it).first << ": " << (*it).second <<endl;
}
}
Output:
Member types:
The member functions can use the following members types as either parameters orreturn type:
Built-in Functions
std::map comes with inbuilt functions. Some of these include:
□ begin()- This function returns the iterator to the first item of the map.
□ size()-This function returns the number of items in a map.
□ empty()-This function returns a Boolean value denoting whether a map is empty.
□ insert( pair(key, value))- This function inserts new key-value pair to a map.
□ find(val)- This function gives the iterator to the val element if it’s found. Otherwise,it will return
m.end().
□ Erase (iterator position)- This function deletes the item at the position pointed bythe iterator.
□ erase(const g)– This function deletes key-value g from a map.
□ Clear ()-This function deletes all items from a map.
Iterating over Map Elements
You can iterate over the map elements. We simply need to create an iterator and use itfor this.
For example:
Example 1:
#include <iostream>
#include <string>
#include <map>
Conclusion: