OOP Lab Manual 2024-25
OOP Lab Manual 2024-25
Lab Manual
Object Oriented Programming
SE- SEM- I
Prepared by
Mrs. Rasika V. Wattamwar
Mrs. Snehal R. Malpani
Mrs. Megha R. Mehar
Vision of Institute
Mission of Institute
VISION of Department
Developing highly skilled and competent IT professional for sustainable growth in the
field of Artificial Intelligence and Data science.
MISSION of Department
Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of
PO12 Life-long Learning
technological change.
Successful Career The ability to employ modern computer languages, environments and
PSO3 and platforms in creating innovative career paths to be an entrepreneur and to
Entrepreneurship have a zest for higher studies.
Course Objectives:
List of Practical’s
Sr. CO PO / PSO
Title of Experiments
No Mapped Mapped
PO-1, PO-4,
Write a C++ program that creates an output file, writes information to PO-5, PO-9,
PO-11, PO-12
4 it, closes the file, open it again as an input file and read the information CO-2
from the file. PSO-1,PSO-2,
PSO-3
PO-1, PO-2,
Write a function template for selection sort that inputs, sorts and PO-4, PO-5,
PO-9, PO-11,
outputs an integer array and a float array. CO-1,
5 PO-12
CO-2
PSO-1,PSO-2,
PSO-3
PO-1, PO-4,
Write C++ program using STL for sorting and searching user defined PO-5, PO-9,
CO-1, PO-11, PO-12
6 records such as Item records (Item code, name, cost, quantity etc)
CO-2
using vector container. PSO-1,PSO-2,
PSO-3
PO-1, PO-2,
Write a program in C++ to use map associative container. The keys PO-4, PO-5,
will be the names of states and the values will be the populations of the PO-9, PO-11,
CO-1,
7 states. When the program runs, the user is prompted to type the name PO-12
CO-2
of a state. The program then looks in the map, using the state name as
PSO-1,PSO-2,
an index and returns the population of the state.
PSO-3
ASSIGNMENT NO. 1
OBJECTIVE:
• To understand the concept of operator overloading.
THEORY:
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
• methods,
• constructors, and
• indexed properties
• It is because these members have parameters only.
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
Rules for Operator Overloading
o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.
ASSIGNMENT NO. 2
THEORY:
Constructor: Constructor in C++ is a special method that is invoked automatically at the time of
object creation. It is used to initialize the data members of new objects generally. The constructor
in C++ has the same name as the class or structure. Constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object which is why it is known as
constructors.
• Constructor is a member function of a class, whose name is same as the class name.
• Constructor is a special type of member function that is used to initialize the data members for
an object of a class automatically, when an object of the same class is created.
• Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
• Constructor do not return value; hence they do not have a return type.
Constructor can be defined inside the class declaration or outside the class declaration
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
Characteristics of constructor
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the class though it can be
declared in the private section of the class.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• Constructor cannot be inherited.
• Addresses of Constructor cannot be referred.
• Constructor make implicit calls to new and delete operators during memory allocation.
Types of Constructors
1.Default Constructor: A constructor without any arguments or with the default value for every
argument is said to be the Default constructor. A constructor that has zero parameter list or in
other sense, a constructor that accept no arguments is called a zero argument constructor or
default constructor.
If default constructor is not defined in the source code by the programmer, then the
compiler defined the default constructor implicitly during compilation. If the default constructor
is defined explicitly in the program by the programmer, then the compiler will not defined the
constructor implicitly, but it calls the constructor implicitly.
3.Copy Constructor: A copy constructor is a member function that initializes an object using
another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class,
a default constructor( without parameters ) should also be explicitly defined as the compiler will
not provide a default constructor in this case. However, it is not necessary but it’s considered to
be the best practice to always define a default constructor. Copy constructor takes a reference to
an object of the same class as an argument.
<class-name> :: ~<class-name>() {
// some instructions
}
A destructor function is called automatically when the object goes out of scope:
• the function ends
• the program ends
• a block containing local variables ends
• a delete operator is called
Static Member Functions and Data Member: Static data members are class members that are
declared using static keywords. A static member has certain special characteristics which are as
follows:
Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
It is initialized before any object of this class is created, even before the main starts.
It is visible only within the class, but its lifetime is the entire program.
Syntax:
static data_type data_member_name;
Static Member Function: Static Member Function in a class is the function that is declared as
static because of which function attains certain properties as defined below:
• A static member function is independent of any object of the class.
• A static member function can be called even if no objects of the class exist.
• A static member function can also be accessed using the class name through the scope
resolution operator.
• A static member function can access static data members and static member functions
inside or outside of the class.
• Static member functions have a scope inside the class and cannot access the current
object pointer.
• You can also use a static member function to determine how many objects of the class
have been created.
The reason we need Static member function:
• Static members are frequently used to store information that is shared by all objects in a
class.
• For instance, you may keep track of the quantity of newly generated objects of a specific
class type using a static data member as a counter. This static data member can be
increased each time an object is generated to keep track of the overall number of objects.
Friend Class: A friend class can access private and protected members of other classes in which
it is declared as a friend. It is sometimes useful to allow a particular class to access private and
protected members of other classes.
We can declare a friend class in C++ by using the friend keyword. For example,
Class one
{
Friend class two;
}
Class two
{
//here class two can access private data members of class one
This pointer: A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address.
The general form of a pointer variable declaration is −
datatype *pointer_name;
C++ provides a keyword 'this', which represents the current object and passed as a
hidden argument to all member functions. The this pointer is a constant pointer that holds the
memory address of the current object. The this pointer is not available in static member
functions as static member functions can be called without any object. static member functions
can be called with class name.
Inline Function: Functions can be instructed to compiler to make them inline so that compiler
can replace those function definition wherever those are being called. Compiler replaces the
definition of inline functions at compile time instead of referring function definition at runtime.
Syntax:
inline returnType functionName(parameters)
{
// code
}
- The use of keyword inline is before the function definition.
- Reduces the function call overhead.
- Inline function is a function that is expanded in line when it is called.
- This substitution is performed by the C++ compiler at compile time.
- Inline function may increase efficiency if it is small.
CONCLUSION: Thus, different concepts of C++ are successfully studied and implemented.
ASSIGNMENT NO. 3
PROBLEM STATEMENT: Imagine a publishing company which does marketing for book
and audio cassette versions. Create a class publication that stores the title (a string) and price
(type float) of publications. 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
instantiates the book and tape class, allows user to enter data and displays the data members. If
an exception is caught, replace all the data member values with zero values.
OBJECTIVE:
• To understand the concept Inheritance in C++.
THEORY:
Inheritance:
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
ASSIGNMENT NO. 4
PROBLEM STATEMENT: Write a C++ program that creates an output file, writes
information to it, closes the file, open it again as an input file and read the information from the
file.
OBJECTIVE:
To understand the concepts File handling in C++
THEORY:
1 ofstream
This data type represents the output file stream and is used to create files and to write
information to files.
2 ifstream
This data type represents the input file stream and is used to read information from files.
3 fstream
This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and read
information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is
used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists, following
will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.
Write an example demonstrating creating, opening, writing and reading from a file.
ASSIGNMENT NO. 5
PROBLEM STATEMENT: Write a function template for selection sort that inputs, sorts and
outputs an integer array and a float array.
OBJECTIVE:
To understand the concept of function template
THEORY:
Template:
Templates are the foundation of generic programming, which involves writing code in
a way 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 of vectors for
example, vector <int> or vector <string>.
You can use templates to define functions as well as classes, let us see how do they
work:
Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be
used within the function definition.
Selection Sort:
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 similar insertion sort. Selection sort is noted for its simplicity, and it has
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in
linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
After two iterations, two least values are positioned at the beginning in the sorted
manner.
The same process is applied on the rest of the items in the array.
ASSIGNMENT NO. 6
PROBLEM STATEMENT: Write C++ program using STL for sorting and searching
user defined records such as Item records (Item code, name, cost, quantity etc) using
vector container.
OBJECTIVE:
THEORY:
STL:
The Standard Template Library (STL) is a set of C++ template classes to provide
common programming data structures and functions such as lists, stacks, arrays, etc. It
is a library of container classes, algorithms, and iterators. It is a generalized library and
so, its components are parameterized. A working knowledge of template classes is a
prerequisite for working with STL.
Algorithms
• The algorithm defines a collection of functions especially designed to be used on
ranges of elements. They act on containers and provide means for various operations
for the contents of the containers.
• Algorithm
• Sorting
• Searching
• Important STL Algorithms
• Useful Array algorithms
• Partition Operations
• Numeric
Containers
• Containers or container classes store objects and data. There are in total seven
standard “first-class” container classes and three container adaptor classes and only
seven header files that provide access to these containers or container adaptors.
• Sequence Containers: implement data structures which can be accessed in a
sequential manner.
• vector
• list
• deque
• arrays
• forward_list( Introduced in C++11)
Functions
• The STL includes classes that overload the function call operator. Instances of such
classes are called function objects or functors. Functors allow the working of the
associated function to be customized with the help of parameters to be passed.
Iterators
• As the name suggests, iterators are used for working upon a sequence of values. They
are the major feature that allow generality in STL.
Utility Library
Sorting:
It is one of the most basic functions applied to data. It means arranging the data in a
particular fashion, which can be increasing or decreasing. There is a builtin function in
C++ STL by the name of sort(). This function internally uses IntroSort. In more details it
is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it
uses QuickSort but if QuickSort is doing unfair partitioning and taking more than
N*logN time, it switches to HeapSort and when the array size becomes really small, it
switches to InsertionSort.
Searching:
It is a widely used searching algorithm that requires the array to be sorted before search
is applied. The main idea behind this algorithm is to keep dividing the array in half
(divide and conquer) until the element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it
returns true otherwise if the middle term is greater than the target, the search is
performed in the left sub-array. If the middle term is less than target, the search is
performed in the right sub-array.
ALGORITHM:
CONCLUSION: Thus, concepts of Vector using STL in C++ are successfully studied
and implemented.
ASSIGNMENT NO. 7
OBJECTIVE:
To learn the concept of map associative container.
THEORY:
erase(const g)– Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map
Examples:
Input : map mymap;
mymap['a'] = 1;
mymap['a'];
Output : 1
Input : map mymap;
mymap["abcd"] = 7;
mymap["abcd"];
Output : 7
//Sample Program
#include <map>
#include <iostream>
#include<string>
usingnamespacestd;
intmain()
{
// map declaration
map<int,string>mymap;
// mapping integers to strings
mymap[1] = "Hi";
mymap[2] = "This";
mymap[3] = "is";
mymap[4] = "DYP";
// using operator[] to print string
// mapped to integer 4
cout<<mymap[4];
return0;
}
Output:
DYP