DSA Lab manual 2024-25
DSA Lab manual 2024-25
1|Page
Laboratory Layout
No of computers available: 26
2|Page
Index
3 Program Outcomes 5
6 List of Experiments 9
3|Page
Vision of the Department
PEO 1: The students of Industrial Engineering shall be prepared to work in any Engineering
organization, pursue higher studies or start their own entrepreneurial project.
PEO 2: Industrial Engineering students shall have the expertise to create the integrated systems of
man machine- material for productivity improvement. Students shall have the ability to provide
financially viable systems.
PEO 3: The students shall have the general understanding and competency of designing and
evaluating the interfacing systems of Information and Technology, Mechanical and Production
Engineering.
PEO 4: Exposure to management courses shall inculcate into the students a sense of professionalism.
Involvement of the graduates with student bodies shall help them shape their personalities as it will
hone their communication skills, build team-spirit and generate social awareness.
PEO 5: The students shall have the desire to pursue higher studies and engage themselves in life-
long learning in the context of technological changes.
Program Outcomes
1. Understand the foundations of the linkage between the quality, productivity and cost.
2. Ability to add value to systems, process, products, services and people
Preface
5|Page
The primary focus of any engineering laboratory/ field work in the technical education system is to
develop the much-needed industry relevant competencies and skills. With this in view, Industrial
Engineering Department embarked on this innovative curriculum for engineering programs with
outcome-based education as the focus and accordingly, relatively large amount of time is allotted for
the practical work. This displays the great importance of laboratory work making each teacher;
instructor and student to realize that every minute of the laboratory time need to be effectively
utilized to develop these outcomes, rather than doing other mundane activities. Therefore, for the
successful implementation of this outcome-based curriculum, every practical has been designed to
serve as a ‘vehicle’ to develop this industry identified competency in every student. The practical
skills are difficult to develop through ‘chalk and duster’ activity in the classroom situation.
Accordingly, the laboratory manual is designed in which the practical programmes are focused on
the outcomes, rather than the traditional age-old practice of conducting practical to ‘verify the
theory’.
This laboratory manual is designed to help all stakeholders, especially the students, teachers and
instructors to develop in the student the pre-determined outcomes. It is expected from each student
that at least a day in advance, they have to thoroughly read through the concerned practical
procedure that they will do the next day and understand the minimum theoretical background
associated with the practical. Every practical in this manual begins by identifying the competency,
industry relevant skills, course outcomes and practical outcomes which serve as a key focal point for
doing the practical. The students will then become aware about the skills they will achieve through
procedure shown there and necessary precautions to be taken, which will help them to apply in
solving real-world problems in their professional life.
In the modem world of Information technology, the Object-Oriented Programming has become
the most preferred approach for software development. It offers a powerful way to cope up with
complexity of real-world problems. Among the OOP languages available, C++ is the primitive
language which develops fundamental understanding of Object-Oriented Concepts. This course
enables students to develop programs in ‘C++’ using Object Oriented Programming approach.
Although best possible care has been taken to check for errors (if any) in this laboratory manual,
perfection may elude us as this is the first edition of this manual. Any errors and suggestions for
improvement are solicited and highly welcome.
Course Syllabus
6|Page
III Semester B.Tech. (Industrial Engineering)
Syllabus
UNIT I:
Concept of a class, Object, Features of Object-Oriented Programming viz. data encapsulation, inheritance and
polymorphism, Need for OOP, Access control of members of a class, constructors, Destructor, Friend
Function.
UNIT II:
C++ Classes and Data Abstraction: Static class members, Constant member functions, Dynamic creation and
destruction of objects, Dynamic memory allocation and de-allocation operators-new and delete
UNIT III:
Polymorphism: Static and Dynamic bindings, Function overloading, Operator overloading, Virtual functions,
Concept of Inheritance, forms of inheritance.
UNIT IV:
Function templates and class templates. Exception Handling: types of exception, throwing an exception, use
of try catch block, user defined exceptions, Re-throwing an exception, Design issues in exception handling,
Benefits of exception handling.
Text Books:
1. Object Oriented Programming Using C++: E. Balaguruswamy, 4th edition. Tata Mcgraw Hill Companies
2. The C++ Programming Language: B. Stroustrup, 4 th edition, Addison Wesley. Reading Mass. USA. May
2013
3. Mastering C++: K Venugopal, Raj Buyya, T ravishankar, 2nd edition, McGraw Hill Education
Reference Books:
1. The Complete Reference: Herbert Schildt, 4th Edition, Tata McGraw Hill
2. Object oriented Programming in C++, 4th Edition, Robert Lafore by Sams Publishing
7|Page
III Semester B.Tech. (Industrial Engineering)
Course Code: INP255 Course: Object Oriented Programming Methods Lab
L: 0 Hrs, T: 0 Hrs. P: 2 Hrs. Per week Total Credits: 01
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Course Outcomes:
S – Strong relation
M – Medium Relation
W – Weak Relation
Empty – No relation
8|Page
List of Practical
Course
Exp
Outcom Aim of Experiment
No
e
CO1 1 Write a program to find largest number in two input arrays.
2 Write a program to show the use of various access controls (Public, private) of
members of a class.
3 Write a program to show passing and returning objects as arguments.
9|Page
List of Industry Relevant Skills
The following industry relevant skills of the competency to develop applications using OOPs
concepts in C++ are expected to be developed in you by undertaking the practical of this laboratory
manual.
1. Develop an application by implementing Inheritance.
2. Develop an application by using Polymorphism.
3. Use appropriate exception handling mechanism for catching all the exceptions
1. For effective implementation and attainment of practical outcomes, in the beginning itself of
each practical, students need to read through the complete write-up including the practical
related questions and assessment scheme of that practical sheet.
2. Student ought to refer the reference books, lab manuals, etc.
3. Student should not hesitate to ask any difficulties they face during the conduct of practical.
4. After performance of the practical, student will write the program in the manual along with
explanation of each line of codes along with the output of the program.
10 | P a g e
CERTIFICATE
Engineering and Management, Nagpur, has successfully completed the term work in
the laboratory of Object-Oriented Programming Methods (INP 255) for the Academic
Date:
11 | P a g e
List of Practical’s and Progressive Assessment Sheet
Date of Dated
Page Date of Mark
SN Practical submissio sign of
No. performance s (15)
n teacher
Write a program to find largest number in two input
1
arrays.
Write a program to show the use of various access
2
controls (Public, private) of members of a class.
Write a program to show passing and returning
3
objects as arguments.
Write a program to show various ways of defining
4
members functions.
Write two separate programs to demonstrate the
5 importance of static data members and static member
functions.
Demonstrate the use of Friend function with an
6
example.
Demonstrate the use of Constructor and Destructor
7
with an example.
How objects can be created dynamically? WAP to
8 demonstrate allocation and deallocation of memory
during run time.
Design a system using a class with suitable member
9 functions and constructors. Use new operator in
constructors to allocate memory space required.
WAP to overload unary operator – with and without
10
using friend operator function.
WAP to multiply two matrices with friend function by
11
overloading binary operator *
Write a program on a real-life application of single
12
inheritance.
Write a program on a real-life application of multiple
13
inheritance
Write a program on a real-life application of
14
Hierarchical inheritance
Write a program on a real-life application of
15
multilevel inheritance
Write a program on a real-life application of
16
hybrid/multipath inheritance.
WAP to demonstrate the use of Virtual functions (run
17
time polymorphism)
18 WAP to demonstrate the use of Function templates
and class templates.
19 Demonstrate the various commonly occurring
exceptions with a suitable program.
20 How exceptions can be handled? WAP to demonstrate
the same using Try-Catch mechanism. Discuss the
design issues in exception handling with its benefits.
12 | P a g e
Practical No: 1
Pre-requirements:
i. Knowledge of header files
ii. Concept of classes and objects
iii. Way of taking user input and displaying results
iv. Function Declaration, Definition, and call
v. Conditional statement - If – else if – else
------------------------------------------------------------------------------------------------------------------------------------
: Background :
1. Header Files: C++ language has numerous libraries that include predefined functions to make
programming easier. In C++ language, header files contain the set of predefined standard library
functions. Your request to use a header file in your program by including it with the preprocessing
directive “#include”. All the header files have a ‘.h’ an extension. By including a header file, we can
use its contents in our program.
Function definitions
Data type definitions
Macros
It offers the above features by importing them into the program with the help of a preprocessor
directive “#include”. These preprocessor directives are used for instructing compiler that these files
need to be processed before compilation. In C program should necessarily contain the header file
which stands for standard input and output used to take input with the help
of scanf() and printf() function respectively.
In C++ program has the header file which stands for input and output stream (iostream.h) used to take
input with the help of “cin” and “cout” respectively.
13 | P a g e
2 . Concept of C++ Classes and Objects
Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined
data type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate
these variables and together these data members and member functions defines the properties
and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body of class is defined
inside the curly brackets and terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Accessing data members and member functions: The data members and member functions of class can be
accessed using the dot(‘.’) operator with the object. For example if the name of object is obj and you want
to access the member function with the name printName() then you will have to write obj.printName() .
14 | P a g e
Accessing Data Members
The public data members are also accessed in the same way given however the private data members are
not allowed to be accessed directly by the object. Accessing a data member depends solely on the access
control of that data member.
This access control is given by Access modifiers in C++.
There are three access modifiers:
public,
private and
protected.
int age;
The statement cout<< “Enter age”; will display the string “Enter age” on to the screen.
The statement cin>>age; will take the value entered by the user into the variable called age;
The statement cout<< “Your age is”<<age; will display the string Your age is followed by the value stored
in the variable age.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts −
Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body − The function body contains a collection of statements that define what the function
does.
15 | P a g e
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you
will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing brace is
reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function
returns a value, then you can store returned value.
You can use these conditions to perform different actions for different decisions.
16 | P a g e
Source Program:
#include<iostream.h>
#include<conio.h>
class number
{
int a, b;
public:
void getdata()
{
cout<<"Enter 2 numbers";
cin >> a >> b;
}
void findlargest()
{
if (a > b)
{
cout<<"\nLargest number is "<< a;
}
else if (a < b)
{
cout<<"\nLargest number is "<< b;
}
else
{
cout<<"\nBoth numbers are same";
}
}
};
void main()
{
clrscr();
number n;
n.getdata();
n.findlargest();
getch();
}
Output:
17 | P a g e
Practical No: 2
Aim: Write a program to show the use of various access controls (Public, private) of members
of a class.
Pre-requirements:
i. Knowledge of Access Control
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Access controls enable you to separate the public interface of a class from the private implementation details
and the protected members that are only for use by derived classes. The access specifier applies to all
members declared after it until the next access specifier is encountered.
The default access is private in a class, and public in a struct or union. Access specifiers in a class
can be used any number of times in any order. The allocation of storage for objects of class types is
implementation-dependent. However, compilers must guarantee assignment of members to
successively higher memory addresses between access specifiers.
Access control helps prevent you from using objects in ways they weren't intended to be used. This
protection is lost when you make explicit type conversions (casts).
18 | P a g e
Source Program:
#include<iostream.h>
#include<conio.h>
// accessing properties of private and public variable, function
// direct access to private variable - is not permitted to outside word
// indirect access to private variable/function - permitted - calling public function
class number
{
private:
int i;
void display()
{ cout<<"Display is called";
}
public:
int j;
void getdata()
{
cout<< “Hello World”;
}
void process()
{
display();
}
};
void main()
{
clrscr();
number n;
n.j=30;// this is permitted as it is declared in the public section
n.getdata(); // yes
n.process(); //yes
n.display(); // NO
getch();
}
Output
19 | P a g e
Practical No: 3
Pre-requirements:
i. Mechanism of passing parameters through functions
------------------------------------------------------------------------------------------------------------------------------------
: Background :
In C++ we can pass class’s objects as arguments and also return them from a function the same
way we pass and return other variables. No special keyword or header file is required to do so.
To pass an object as an argument we write the object name as the argument while calling the
function the same way we do it for other variables.
Syntax:
function_name(object_name);
In this program, we have created a function createStudent() that returns an object of Student class.
We have called createStudent() from the main() method.
Here, we are storing the object returned by the createStudent() method in the student1.
20 | P a g e
Source Code
#include<iostream.h>
#include<conio.h>
class number
{
public:
int i,j; int i =10; this is not allowed here
void getdata()
{
i=10;
j=20;
}
number process(number m)// n object is catched. So contents of n will be copied to object m
{
m.i =100;
m.j=200;
return(m); //return m object to calling function process.
}
};
void main()
{
clrscr();
number n,n1;
n.getdata();
n1= n.process(n); //throw object n to m and collect back m to n1.
//accessing contents of n1 object
cout<<"i = "<<n1.i;
cout<<"\nj= "<<n1.j;
//accessing contents of n object
cout<<"\n\ni="<<n.i;
cout<<"\nj="<<n.j;
//accessing content of m object
// cout<<"\n\ni="<<m.i;
// cout<<"\nj="<<m.j;
getch();
}
Output
Pre-requirements:
i. Difference between Defining and declaring functions
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Member functions are the functions, which have their declaration inside the class definition and works on the
data members of the class. The definition of member functions can be inside or outside the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if its defined outside
the class, then we have to use the scope resolution :: operator along with class name along with function
name.
For example:
class Cube
{
public:
int side;
int getVolume(); // Declaring function with no argument and return type int.
};
If we define the function inside class then, we can directly declare and define the function as below.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
But if we plan to define the member function outside the class definition then we must declare the
function inside class definition and then define it outside.
class Cube
{
public:
int side;
int getVolume();
}
int Cube :: getVolume() // member function defined outside class definition
{
return side*side*side;
}
The main function for both the function definition will be same. Inside main() we will create object of class,
and will call the member function using dot . operator.
22 | P a g e
Source Code
class student
{
private:
int age, height;
public:
void getdata() // function declaration and declaration inside the class
{
cout<<“Enter age and height of student”;
cin>>age>>height;
}
void main()
{
student s1;
s1.getdata();
s1.showdata();
}
Output window
23 | P a g e
Practical No: 5
Aim: Write two separate programs to demonstrate the importance of static data members and
static member functions.
Pre-requirements:
Understanding of
i. Static data members
ii. Static member functions
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Static data members are class members that are declared using static keywords. A static member has certain
special characteristics. These are:
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 being created, even before main starts.
It is visible only within the class, but its lifetime is the entire program
A static member is shared by all objects of the class. All static data is initialized to zero when the first object
is created, if no other initialization is present. We can't put it in the class definition but it can be initialized
outside the class as done in the following example by redeclaring the static variable, using the scope
resolution operator :: to identify which class it belongs to.
By declaring a function member as static, you make it independent of any particular object of the class. A
static member function can be called even if no objects of the class exist and the static functions are accessed
using only the class name and the scope resolution operator ::.
A static member function can only access static data member, other static member functions and any other
functions from outside the class.
Static member functions have a class scope and they do not have access to the this pointer of the class. You
could use a static member function to determine whether some objects of the class have been created or not.
24 | P a g e
Source Code
#include<iostream.h>
#include<conio.h>
//Aim- to understand static data members and its use
class item
{
static int count; // static variable declaration
int number;
public:
void getcount(int a)
{
number=a;
count = count+1; //increment of static variable
}
void showcount()
{
cout<<"\nThe value of number is "<<number; // normal variable
cout<<"\n the value of Static variable "<<count;// static variable
}
};
void main()
{
clrscr();
item x,y,z; // created two object of class item count = 0
x.getcount(10);// number =10, count = 1
y.getcount(20);// number = 20, count = 2
z.getcount(30); // number = 30, count = 3
cout<<"\n\n____________________\n\n";
x.showcount();
y.showcount();
z.showcount();
getch();
}
Output Window:
25 | P a g e
Practical No: 6
Aim: Write the characteristics of Friend function. And demonstrate the friend function with
the program.
Pre-requirements:
i. Friend function
ii. Properties of friend functions
------------------------------------------------------------------------------------------------------------------------------------
: Background :
According to the data hiding concept in C++, no one has the permission to access private and protected
members from outside the class. If a developer needs access to the private or protected members, then the
developer can use friend functions. A friend function provides privileges to access all the private and
protected members of the class.
26 | P a g e
Source Code
#include<iostream.h>
#include<conio.h>
class numbers
{
int a, b;
public:
void getdata() //normal member function declaration and definition
{
a=100;
b=200;
}
27 | P a g e
Practical No: 7
Aim: Write characteristic of constructors. Write a program to demonstrate the use of various
constructors in one program and destruct the objects after its use is over.
Pre-requirements:
i. Constructors and its types
ii. Destructor
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Constructor:
A constructor is a member function of a class that has the same name as the class name. It helps to initialize
the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of
the class. It is called whenever an instance of the class is created. It can be defined manually with arguments
or without arguments. There can be many constructors in a class. It can be overloaded but it cannot be
inherited or virtual. There is a concept of copy constructor which is used to initialize an object from another
object.
Syntax:
ClassName()
{
//Constructor's Body
}
Default Constructor
Parametrized Constructor
Copy Constructor
Destructor:
Like a constructor, Destructor is also a member function of a class that has the same name as the class name
preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while the object of
the class is freed or deleted. In a class, there is always a single destructor without any parameters so it can’t be
overloaded. It is always called in the reverse order of the constructor. if a class is inherited by another class
and both the classes have a destructor then the destructor of the child class is called first, followed by the
destructor of the parent or base class.
Syntax:
~ClassName()
{
//Destuctor's Body
}
28 | P a g e
Source Code
// aim - to understand default/empty constructor
#include<iostream.h>
#include<conio.h>
class constructor
{
static int count;
public:
constructor() // empty constructor. No argument inside round brackets
{
count= count +1;
}
void show()
{
cout<<"\nCount = "<<count;
}
};
void main()
{
clrscr();
constructor c,c1;
c.show();
c1.show();
getch();
}
Output Window
Count = 1
Count =2
class numbers
{
int a,b,d;
float c,e;
public:
numbers()
{
a=b=c=d=e=0;
}
29 | P a g e
numbers(int x, int y) //param. constructor having two parameters
{
a=x;
b=y;
c=d=e=0;
}
void show()
{
cout<<"\n a="<<a;
cout<<"\n b="<<b;
cout<<"\n c="<<c;
cout<<"\n d="<<d;
cout<<"\n e="<<e;
}
};
void main()
{
clrscr();
numbers n; //default constructor
30 | P a g e
//aim - to understand copy constructor
// it is used to copy already created object into new object
#include<iostream.h>
#include<conio.h>
class numbers
{
int num;
public:
numbers()
{
num =0;
}
numbers(int x) //param. const. decl. and def.
{
num=x;
}
numbers(numbers &p) //copy cons. decl. and def, collecting address of object which is passed
{
num=p.num; // u r copying content of n.num into num ->n2
}
void showdata()
{
cout<<"\nNumber ="<<num;
}
};
void main()
{
clrscr();
numbers n;// this statement is not param. , copy
numbers n1(2);//param. const.this will call param. contr.
//numbers n2(n);//passing the object and its address will get collected
numbers n2 = n1; // int n = 2;
//numbers n3 =n; u can also pass object of default constr.
n.showdata();// showing contents of default co.
n1.showdata();// showing contents of param.
n2.showdata();// showing contesnts of copy con.
getch();
}
Output Window
31 | P a g e
Practical No: 8
Aim: How objects can be created dynamically? WAP to demonstrate allocation and
deallocation of memory during run time.
Pre-requirements:
i. Memory allocation de-allocation operator new and delete
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Dynamic Objects -Memory allocation and Deallocation using new and Delete
As discussed earlier, C++ supports dynamic memory allocation/deallocation. C++ allocates memory
and initializes the member variables. An object can be created at run time; such an object is called a
dynamic object. The construction and destruction of the dynamic object is explicitly done by the
programmer. The new and delete operators are used to allocate and deallocate memory to such
objects.
A dynamic object can be created using the new operator as follows:
ptr = new classname;
The new operator returns the address of the object created, and it is stored in the pointer ptr. The
variable ptr is a pointer object of the same class. The member variable of the object can be accessed
using the pointer and -> (arrow) operator. A dynamic object can be destroyed using the delete
operator as follows:
delete ptr;
The delete operator destroys the object pointed by the pointer ptr. It also invokes the destructor of a
class. The following program explains the creation and destruction of dynamic objects:
Source Code
/Write a program to create dynamic object.
#include<iostream.h>
#include<conio.h>
class data
{
int x,y;
public:
data()
{
cout«"\n Constructor";
x=10;
y=50;
}
~data()
{ cout«"\n Destructor"; }
32 | P a g e
void display()
{
cout«"\n x="«x; cout«"\n y="«y;
}
};
void main()
{
clrscr();
data *d; // declaration of object pointer
d=new data; // dynamic object created
d->display();
delete d; // deleting dynamic object
getch();
}
Output window
Constructor
x=10
y=50
Destructor
Explanation:
33 | P a g e
Practical No: 9
Aim: Design a system using a class with suitable member functions and constructors.
Pre-requirements:
i. Fundamentals covered till now
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Problem Question:
A book shop maintains the inventory of books that are being said at the shop. The list includes
details such as author, title, price, publisher and stock position. Whenever a customer wants a book,
the sales person inputs the title and author and the system searches the list and displays whether it is
available or not. If it is not, an appropriate message is displayed. If it is, then the system displays the
book details and requests for the number of copies required. If the requested copies are available, the
total cost of the requested copies is displayed; otherwise, the message "Required copies not in stock"
is displayed.
Design a system using a class called hooks with suitable member functions and constructors. Use
new operator in constructors to allocate memory space required.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
//declaration of class books
class books
{
public:
char author[20];
char title[20];
char publisher[50];
int price;
int copies;
int stock;
stock=1;
34 | P a g e
}
void main()
{
clrscr();
books bk;
bk.setData();
bk.check();
getch();
}
Output Window
35 | P a g e
Practical No: 10
Pre-requirements:
i. Concept of polymorphism
ii. Understanding of function overloading
------------------------------------------------------------------------------------------------------------------------------------
: Background :
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at
the same time can have different characteristics. Like a man at the same time is a father, a husband, an
employee. So, the same person possesses different behavior in different situations. This is called
polymorphism. Polymorphism is considered as one of the important features of Object-Oriented
Programming.
Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator
overloading.
Creating two or more members that have the same name but are different in number or type of parameter is
known as overloading.
In C++, we can overload:
Methods
Constructors
Operators
Types of overloading
Function overloading
The process of having two or more functions with the same name, but different parameters, is known as
function overloading.
The function is redefined by either using different types of arguments or a different number of arguments. It is
only through these differences that a compiler can differentiate between functions.
The advantage of function overloading is that it increases the readability of a program because you don’t need
to use different names for the same action.
36 | P a g e
Sources Code
// C++ program for function overloading
#include<iostream.h>
#include<conio.h>
class numbers
{
float x,y;
public:
void getdata()
{
cout<<"\nEnter the values of x and y";
cin>>x>>y;
}
void getdata( float a, float b)
{
x=a;
y=b;
}
void getdata(int a, int b)
{
x=a; y=b;
}
void add()
{
cout<<"\nThe addition of the variables x and y ="<<(x+y);
}
};
void main()
{
clrscr();
numbers n1,n2,n3;
n1.getdata();
n2.getdata(float(2.4),float(5.6));
n3.getdata(4,5);
cout<<"\n\n_____________________________";
n1.add();
n2.add();
n3.add();
getch();
}
37 | P a g e
Practical No: 11
Pre-requirements:
i. Concept of polymorphism
ii. Understanding of operator overloading
------------------------------------------------------------------------------------------------------------------------------------
: Background :
1. Existing operators can only be overloaded, but the new operators cannot be overloaded.
2. The overloaded operator contains atleast one operand of the user-defined data type.
3. We cannot use friend function to overload certain operators. However, the member function can be
used to overload those operators.
4. 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.
5. 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.
38 | P a g e
Source Code
#include<iostream.h>
#include<conio.h>
class numbers
{
int x,y;
public:
void getdata()
{
cout<<"Enter x and y";
cin>>x>>y;
}
friend void operator-(numbers &n) // if you write simply numbers n so it will crate a copy
{
// of n1 object i.e. n = n1; but if u write &n -- if u change the content of n object, it will reflect in n1 object as well
n.x= -n.x; // x=-x;
n.y = -n.y; //y=-x;
}
void showdata()
{
cout<<"\nX ="<<x;
cout<<"\nY ="<<y;
}
};
void main()
{
clrscr();
numbers n1;
n1.getdata();
cout<<"\nBefore changing the signs\n";
n1.showdata();
-n1;// this will pass the object to operator - function
cout<<"\nAfter changing the signs\n";
n1.showdata();
getch();
}
Output Window
39 | P a g e
// program to overload the binary operators.
#include <iostream.h>
class A
{
int x;
public:
A()
{
}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output Window:
40 | P a g e
Practical No: 12
Pre-requirements:
i. Concepts of inheritance
ii. Types of Inheritance
------------------------------------------------------------------------------------------------------------------------------------
: Background :
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.
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(),
capacity(), applyBrakes() will be same for all of the three classes. If we create these classes avoiding
inheritance then we have to write all of these functions in each of the three classes as shown in below figure:
You can clearly see that above process results in duplication of same code 3 times. This increases the
chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we
create a class Vehicle and write these three functions in it and inherit the rest of the classes from the
vehicle class, then we can simply avoid the duplication of data and increase re-usability. Look at
the below diagram in which the three classes are inherited from vehicle class:
41 | P a g e
Using inheritance, we have to write the functions only one time instead of three times as we have inherited
rest of the three classes from base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have to
follow the below syntax.
Syntax:
Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit this
sub class for example: public, private etc. and base_class_name is the name of the base class from which you
want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent
object, which contains any private members which that class declares.
In the below program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data
members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
Public mode: If we derive a sub class from a public base class. Then the public member of
the base class will become public in the derived class and protected members of the base
class will become protected in derived class.
Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
Private mode: If we derive a sub class from a Private base class. Then both public member
and protected members of the base class will become Private in derived class.
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
42 | P a g e
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
The below table summarizes the above three modes and shows the access specifier of the members of base
class in the sub class when derived in public, protected and private modes:
Source Code
#include <iostream.h>
// Base class
class Parent
{
public:
int id_p;
};
class Child : public Parent // Sub class inheriting from Base Class(Parent)
{
public:
int id_c;
};
void main()
{
Child obj1;
// An object of class child has all data members and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is: " << obj1.id_c << '\n';
cout << "Parent id is: " << obj1.id_p << '\n';
}
Output Window
Child id is 7
Parent id is 91
43 | P a g e
Inheritance Types
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub
class is inherited by one base class only.
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more
than one classes. i.e one sub class is inherited from more than one base classes.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived
class.
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a single base class
1. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of
inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
2. A special case of hybrid inheritance: Multipath inheritance: A derived class with two base classes
and these two base classes have one common base class is called multipath inheritance. An ambiguity
can arise in this type of inheritance.
44 | P a g e
Source Code
//C++ program to explain Single Inheritance
#include<iostream.h>
using namespace std;
};
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
45 | P a g e
Practical No: 13
Pre-requirements:
i. Structure of Multiple inheritance
------------------------------------------------------------------------------------------------------------------------------------
Source Code
#include<iostream.h>
#include<conio.h>
46 | P a g e
Practical No: 14
Pre-requirements:
i. Structure of Hierarchical inheritance
------------------------------------------------------------------------------------------------------------------------------------
Source Code
#include<iostream.h>
#include<conio.h>
class student
{
char name[20];
int rollno;
public: Student
void getdata()
{
cout<<"\nEnter Name and Roll no\n"; Internal Incentive
cin>>name;
cin>>rollno;
}
void showdata() Result
{
cout<<"\nName ="<<name;
cout<<"\nRoll no= "<<rollno;
}
};
class internal : public student
{
float mark1, mark2,assignmarks;
public:
void gettestmarks()
{
cout<<"\nEnter marks obtained in two subjects";
cin>>mark1>>mark2;
}
void getassignmentmarks()
{
cout<<"\nEnter assignment marks";
cin>>assignmarks;
}
47 | P a g e
void showmarks()
{
cout<<"\nMarks obtained\n";
cout<<"mark1 ="<<mark1;
cout<<"\nmark2 ="<<mark2;
cout<<"Assignment marks="<<assignmarks;
}
};
class incentive : public student
{
char grade[5];
public:
void getgrade()
{
cout<<"\nEnter Grade";
cin>>grade;
}
void showgrade()
{
cout<<"\nGrade ="<<grade;
}
};
class result : public internal
{
char res[20], total,extmarks;
public:
void getextmarks()
{
// entering test marks out 30
// assign marks out of 10
48 | P a g e
void main()
{
clrscr();
result r;
r.getdata(); // students info
r.gettestmarks();// internal - test marks
r.getassignmentmarks();// internal - assignment
r.getextmarks(); // external marks
// displaying information
r.showdata(); // display student details
r.showmarks();// internal marks
r.calculate();// result
getch();
}
Output Window
49 | P a g e
Practical No: 15
Pre-requirements:
i. Structure of multilevel inheritance
------------------------------------------------------------------------------------------------------------------------------------
Source Code
// main function
int main()
50 | P a g e
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Practical No: 16
51 | P a g e
Date of Performance: ____________________
Pre-requirements:
i. Structure of hybrid/multipath inheritance.
------------------------------------------------------------------------------------------------------------------------------------
: Source Code :
#include<iostream.h>
// base class
Vehicle Fare
class Vehicle
{
public:
Vehicle() Car Bus
{
cout << "This is a Vehicle\n";
}
};
//base class
class Fare
{
public:
Fare()
{
cout << "Fare of Vehicle\n";
}
};
};
};
52 | P a g e
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}
Multipath Inheritance
#include<iostream.h>
class ClassA
{
public: Class A
int a;
};
int main()
{
ClassD obj;
53 | P a g e
obj.a = 10; // Statement 3
obj.a = 100; // Statement 4
obj.b = 20;
obj.c = 30;
obj.d = 40;
Practical No: 17
54 | P a g e
Date of Performance: ____________________
Aim: WAP to demonstrate the use of Virtual functions (run time polymorphism)
Pre-requirements:
i. Virtual functions knowledge
------------------------------------------------------------------------------------------------------------------------------------
: Background :
Polymorphism refers to the property by which objects belonging to different classes are able to respond to the
same message but in different forms. When there are C++ functions with the same name in both superclass as
well as a subclass, virtual functions gives programmer capability to call a member function of a different class
by the same function call based upon different context. This feature is known as polymorphism which is one
of the important features of OOP. The pointer is also one of the key aspects of C++ language similar to that of
C. In this chapter, we will be dealing with virtual functions and pointers of C++.
A virtual function is a special form of member function that is declared within a base class and redefined by a
derived class. The keyword virtual is used to create a virtual function, precede the function's declaration in the
base class. If a class includes a virtual function and if it gets inherited, the virtual class redefines a virtual
function to go with its own need. In other words, a virtual function is a function which gets override in the
derived class and instructs the C++ compiler for executing late binding on that function. A function call is
resolved at runtime in late binding and so compiler determines the type of object at runtime.
1. Write a program to declare virtual function and execute the same function defined in the base and
derived class.
55 | P a g e
#include<iostream.h>
#include<conio.h>
class first
{
int b;
public:
first()
{
b=10;\
}
virtual void display()
{
cout«“\n b=" «b;
}
};
class second : public first
{
int d;
public:
second()
{
d=20;
}
void display()
{
cout«"\n d="«d;
}
};
void main()
{
clrscr();
first f ,*p;
second s;
p=&f;
p->display():
p=&s;
p->display():
}
Output Window
b = 10
d = 20
Explanation:
The above program is similar to the previous one. The only difference is that a virtual keyword precedes the
display() function of the base class as per the statement virtual void display() {cout«“\n b = ”«b;}. The virtual
keyword does the run-time binding. In the first call, the display() function of the base class is executed and in
the second call, that is, after assigning the address of the derived class to pointer p, displays() function of the
derived class is executed.
2. Write a program to use pointer for both base and derived class and call the member function. Use
virtual keyword.
#include<iostream.h>
56 | P a g e
#include<conio.h>
class super
{
public:
virtual void display()
{
cout«“\n In function display() class super";
}
virtual void show()
{
cout«"\n In function show() class super”;
}
}
class sub : public super
{
public:
void display()
{
cout«"\nln function display() class sub";
}
void show()
{
cout«"\n In function show() class sub";
}
};
void main()
{
clrscr();
super S;
sub A;
super *point;
cout«"\n Pointer point points to class super\n";
point=&S;
point->display();
point->show();
cout«"\n\n Now Pointer point points to derived class sub\n”;
point=&A;
point->display();
point->show();
getch();
}
Output Window
Pointer point points to class super
In function display() class super
In function show() class super
Now Pointer point points to derived class sub
In function display() class sub
In function show() class sub
Explanation:
In the above program, the base class super and the derived class sub have member functions a similar name.
They are display() and show(). In function main(), the variable S is an object of class super, and the variable A
is an object of derived class sub. The pointer variable point is a pointer to the base class. The address of object
57 | P a g e
S is assigned to the pointer S. The pointer calls both the member functions. Similarly, the variable A is an
object of the derived class sub. The address of A is assigned to the pointer point and again, the pointer calls
the member functions.
The member functions of the base class are preceded by the keyword virtual. If the virtual keyword is
removed, in both the function calls, the member functions of the base class are executed. The member
functions for the derived class are not executed, though the pointer has the address of the derived class. If the
virtual keyword is not removed, firstly, the member function of the base class is executed, and then member
function of derived class.
Practical No: 18
58 | P a g e
Aim: WAP to demonstrate the use of Function templates and class templates.
Pre-requirements:
i. Generic Programming
ii. Function templates and class templates
------------------------------------------------------------------------------------------------------------------------------------
: Background :
GENERIC PROGRAMMING
Templates in C++
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter
so that we don’t need to write the same code for different data types. For example, a software company may
need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one
sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can
always be replaced by keyword ‘class’.
How templates work?
Templates are expanded at compiler time. This is like macros. The difference is, compiler does type checking
before template expansion. The idea is simple, source code contains only function/class, but compiled code
may contain multiple copies of same function/class.
Function Template
template <class T>
T Large(T n1, T n2)
{
If (n1>n2)
return n1;
else
return n2;
}
void main ()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value”
}
Output
Enter two integers:
5
10
10 is larger.
59 | P a g e
Enter two floating-point numbers:
12.4
10.2
12.4 is larger.
In the above program, a function template Large() is defined that accepts two arguments n1 and n2 of data
type T. T signifies that argument can be of any data type.
Large() function returns the largest among the two arguments using a simple conditional operation.
Inside the main() function, variables of three different data types: int, float and char are declared. The
variables are then passed to the Large() function template as normal functions.
During run-time, when an integer is passed to the template function, compiler knows it has to generate a
Large() function to accept the int arguments and does so.
Similarly, when floating-point data and char data are passed, it knows the argument data types and generates
the Large() function accordingly.
This way, using only a single function template replaced three identical normal functions and made your
code maintainable.
Example 2
template <typename T>
void Swap (T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
void main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "\n\nAfter passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
60 | P a g e
}
Class Templates
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that is same for all classes, only the data types used are
different.
Normally, you would need to create a different class for each data type OR create different member
variables and functions within a single class.
This will unnecessarily bloat your code base and will be hard to maintain, as a change is one
class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
61 | P a g e
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
return 0;
}
Output Window
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
62 | P a g e
It also contains public member functions to calculate the addition, subtraction, multiplication and division
of the numbers which return the value of data type defined by the user. Likewise, a function
displayResult() to display the final output to the screen.
In the main() function, two different Calculator objects intCalc and floatCalc are created for data types: int
and float respectively. The values are initialized using the constructor.
Notice we use <int> and <float> while creating the objects. These tell the compiler the data type used for
the class creation.
This creates a class definition each for int and float, which are then used accordingly.
Then, displayResult() of both objects is called which performs the Calculator operations and displays the
output.
Practical No: 19
Pre-requirements:
i. Exception handling
------------------------------------------------------------------------------------------------------------------------------------
: Background :
An exception is a problem that arises during the execution of a program. A C++ exception is a response to
an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling
is built upon three keywords: try, catch, and throw.
1. throw − A program throws an exception when a problem shows up. This is done using a throw
keyword.
2. catch − A program catches an exception with an exception handler at the place in a program where
you want to handle the problem. The catch keyword indicates the catching of an exception.
3. try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of the try and
catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch as follows –
try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your try block raises
more than one exception in different situations.
Throwing Exceptions
64 | P a g e
Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw
statement determines a type for the exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.
try {
// protected code
}
catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should
handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the
parentheses enclosing the exception declaration as follows −
try {
// protected code
}
catch(...)
{
// code to handle any exception
}
65 | P a g e
#include <iostream.h>
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try
{
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we have to use
const char* in catch block. If we compile and run above code, this would produce the following result −
Division by zero condition!
66 | P a g e