Final OOPs and C++ Lab Book
Final OOPs and C++ Lab Book
Student Name:
College Name:
Academic Year:
CERTIFICATE
2
Editorial Board:
1. Mrs. Shubhangi K. Patil
Assistant Professor, ATSS College of Business Studies and Computer Application,
Chinchwad
2. Ms. Sonali Kadwadkar
Assistant Professor, ATSS College of Business Studies and Computer Application,
Chinchwad
3. Mrs. Reshma Masurekar
Assistant Professor, Pad. Dr. D. Y. Patil Arts, Commerce and Science College, Pimpri
4. Mrs. Vidya Shinde
Assistant Professor, Pad. Dr. D. Y. Patil Arts, Commerce and Science College, Pimpri
5. Mrs. Anupama Algannawar
Assistant Professor, MIT Arts, Commerce and Science College Alandi
6. Dr. Manjusha Patil
Reviewed By:
1. Dr. Ranjit Patil
Pad. Dr. D. Y. Patil Arts, Commerce and Science College, Pimpri
2. Dr. Madhuri Deshpande
S.P. College, Pune
3. Dr. Vinaya Keskar
ATSS College of Business Studies and Computer Application, Chinchwad
3
Introduction
This workbook is intended to be used by F. Y. B. Sc. (AI & ML) Semester-I students for the
practical course based on AIML-101-T (Object Oriented concepts and Programming using C++). It
is designed by considering all the practical topics mentioned in the syllabus.
Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
4
4. Instructions to the Instructors:
Explain the assignment and the related concepts to students in approximately ten minutes.
Use the whiteboard if necessary or demonstrate using the software.
Evaluate each student's assignment on a scale of 5 by ticking the appropriate box, and
record the score on the assignment completion sheet for the respective section.
5
Assignment Completion Sheet
a 1 Introduction to C++
2 a. Array of object
b. Constructor and Destructor
c. Static and Inline functions
d. Function & Operator overloading
3 Inheritance
4 a. Exception handling
b. Template
Total out of 40
a. Total out of 10
b. Total out of 5
6
Assignment No. 1: Introduction to C++
1. Introduction:
In 1982, Bjarne Stroustrup started to develop a successor to C with Classes at Bell labs,
which he named "C++", as it is an extension to C programming language. C++ runs on a
variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. The
major purpose of C++ programming is to introduce the concept of object orientation to the
C programming language.
C++ is a general purpose, object oriented programming language. C++ has some
additional facilities to those in C such as classes, data binding, data hiding, inheritance,
encapsulation, polymorphism, default function argument etc. because of which it allows
code to be reused and lowering development costs.
Example: C++ Hello world program to simply print "Welcome to C++
Programming" on computerscreen.
// My first C++ program
#include <iostream.h>
int main()
7
{
cout<< " Welcome to C++ Programming ";
return 0;
}
• Operator:
In C++ input and output are performed in the form of a sequence of bytes or more commonly
known as streams. Streams are of two types, if the direction of flow of bytes is from the device like
keyboard to main memory then it is an Input Stream and if the direction of flow of bytes is from
main memory to device like display screen then it is an output stream.
8
C++ is able to input and output the built-in data types using the stream extraction operator
>> and the stream insertion operator << respectively. iostream stands for standard input-output
stream in C++, this header file contains definitions to objects like cin, cout etc.
1.2 Class:
A class in C++ is just an extension of a „structure‟ used in the „C‟ language. Class is a user- defined
data type. It actually binds the data and its related functions in one unit, they are called members of
the class.
A structure and a class differ a lot as a structure has limited functionality and features as compared
to a class. A structure is used to represent a record and a class can have both data members and
functions also. C++ expands the role of structure to create a class.
The Structure and Class, are almost similar in all respect except the significant one difference that,
structure by default have all its member as “public”, and class by default have all its member
“private”. Both a structure and a class provide a way to create a customized data type which can be
used further to create instances. Instance of structure is called „structure variable‟ and instance of a
class is called „object‟.
1.3 Object:
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.
When you define a class, you define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
9
of and what operations can be performed on such an object.
1.4 Access Specifiers:
Access specifiers are used to implement an important feature of Object-Oriented Programming
known as Data hiding. Access specifiers in a class define how the data members and functions of a
class can be accessed. That is, it sets some restrictions on the class members not to get directly
accessed by the outside functions. This access restriction to the class members is specified by the
labeled public, private, and protected sections within the class body. The keywords public, private,
and protected are called access specifiers.
public - members are accessible from outside the class but within a program.
private - members cannot be accessed or viewed from outside the class. Only the class and
friend functions can access private members.
protected - members cannot be accessed from outside the class, however, they can be
accessed in inherited classes.
Example: C++ program to demonstrate class, object, access specifiers and defining
member function inside class definition
#include <iostream.h>
class Rectangle
{
private:
double length;
double width;
public void setDimensions(double l, double w)
{
length = l;
width = w;
}
double getLength()
{
return length;
}
double getWidth()
10
{
return width;
}
double area()
return length * width;
}
};
int main()
{
Rectangle rect;
rect.setDimensions(7.5, 4.2);
return 0;
The scope resolution operator informs the compiler what class the member belongs to.
Defining a member function outside a class requires the function declaration (function
prototype) to be provided inside the class definition.
11
for a class, static data members are used.
5. Write a C++ program to implement a class called Circle that has private member variables
for radius. Include member functions to calculate the circle's area and circumference.
Set B
1. Write a C++ Program to print the following pattern
1
232
34543
4567654
567898765
12
2. Write a C++ Program to print following pattern
*********
*******
*****
***
*
3. Create a C++ Program with a Class Student that uses this pointer to set and display member
variables. Declare at least two objects and assign values using this pointer.
4. Write a C++ Program that uses a static variable inside a function to keep track of the number of
times the function is called. Call the functions multiple times from main() to demonstrate that static
variable retains its values across calls.
5. Write a C++ program to swap two numbers using reference variables and display the values
before and after swapping in main().
Set C
Case Study 1: Functionality of Camera
Question: Define a class called Camera with data : resolution in Pixel of the camera, company
name, and member functions on(), off(), takepicture().
Case Study 2: Functionality of Phone
Question: Define a class called Phone with attributes Company name, Phone number and
functions such as on(), off(), Call(), message()
Assignment Evaluation
13
Assignment 2: a. Array of Objects
To Learn about:
Array of Object
Reading:
You should read following topics before starting this exercise:
Array
Object
Array of object
Ready References:
An object of class represents a single record in memory, to create more than one record of class
type, an array of object is used. An array that contains the class type of element is called array of
objects. Array of objects contains the objects of the class as its individual elements. It is declared in
the same way as an array of any built-in data type.
Example 1: C++ program to illustrate use of array of objects.
#include<iostream.h>
class Employee
{
int Emp_id;
char Name[20];
long Salary;
public:
void Accept()
{
cout<<"\n\tEnter Employee Id, Name and Salary : ";
cin>>Emp_id>>Name>>Salary;
}
void Display()
{
cout<<"\n"<<Emp_id<<"\t"<<Name<<"\t"<<Salary;
}
};
int main()
{
int i;
14
Employee emp[3]; //Creating Array of objects to store 3 Employees details
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
emp[i].Accept();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
emp[i].Display();
return 0;
}
Above program will accept and display details of 3 employees using array of objects.
In C++ objects of a class can be passed as arguments, the same way how we pass other variables.
To pass it, the object name as the argument is used while calling the function. Object as function
argument is normally used to communicate between two objects.
The objects of a class can be passed as arguments to member functions as well as non-member
functions either by value or by reference.
Call by value: When an object is passed by value, a copy of the actual object is created
inside the function, to pass entire object into another function. This copy is destroyed
when the function terminates. Moreover, any changes made to the copy of the object
inside the function are not reflected in the actual object.
Call by reference: In this method, only a reference to that object (not the entire object) is
passed to the function. Thus, the changes made to the object within the function are also
reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data mem bers
can be accessed inside the function using the object name and the dot operator. However, the data
members of the calling object can be directly accessed inside the function without using the
object name and the dot operator.
15
2. Write a C++ program to create a class Person with data members Person_name and
Person_age. Write member function to accept and display information of „n‟ Persons. (Use
constructor to accept Person information)
3. Write a C++ program to create a class Student with data members Stud_name, Stud_age,
and Grade. Initialize an array of Student objects. Write a member function to print the
details of students who scored a grade „O‟. (Use Grade: O, A, B, C, D)
4. Write a C++ program to create a class Employee with data members Emp_id, Emp_Name,
Company_Name, Emp_Salary. Write member functions to accept and display information
of „n‟ Employees.
Set B:
1. Write a C++ program to create a class City with data members City_code, City_name,
population. Write necessary member functions for the following:
i. Accept details of n cities
ii. Display details of n cities where City_name starts with „P‟.
2. Write a C++ program to create a class Person with data members Person_name and Contact
number. Write necessary member functions for the following:
i. Accept details of n Person
ii. Display details of n Persons
iii. Display details of Person with specified contact number.
3. Write a C++ program to create a class Account with data members Acc_number, Acc_type
and Balance. Use dynamic memory allocation to accept „n‟ account details and display it.
Set C:
Case Study 1: Library Management System
Question: Develop a Library Management System to manage a collection of books with
data members as Book_title, Book_author, Book_Publication_Year and Book_ISBN. Write
necessary member functions for the following:
i. To accept book details from user
ii. To search for a book by using ISBN and also analyze the time complexity of the
SearchBookByIsbn() function
16
Product_category and Product_Price and Stock. Write necessary member functions for the
following:
i. To Add new products
ii. To Update existing products
iii. To Retrieve products based on different criteria (e.g., category, price range)
Practice Program:
1. Write a C++ program to create a class Employee with data members Emp_Id, Emp_Name,
Mobile_No., Salary. Write necessary member functions for the following:
i. Accept details of n employees
ii. Serach details of a particular employee.
(Use Array of object)
2. Write a C++ program to create a class Mobile for inventory of mobiles with data members
Mobile_Company, Model, Color, Price and quantity. Mobile can be sold, if stock is
available, otherwise purchase will be made. Write necessary member functions for the
following:
i. To accept mobile details from user.
ii. To sale a mobile. (Sale contains Mobile details & number of mobiles to be sold.)
iii. To Purchase a Mobile. (Purchase contains Mobile details & number of mobiles to
be purchased)
Assignment Evaluation
_________________________________________________________________________
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]
17
b. Constructor and Destructor
To learn about:
• Constructor.
• Types of Constructor.
• Constructors with default arguments
• Dynamic Initialization of object
• Destructor
Reading
You should read following topics before starting this exercise:
• Classes and Objects
• Member Functions
• Default Argument
• Characteristics of Constructor
• Characteristics of Destructor
Ready References
2.2 Constructor:
A constructor is a „special‟ member function whose task is to initialize the objects of its
class. It is called constructor because it constructs the values of data members of the class.
Constructor is automatically called when object of class is created.
Characteristics of Constructor:
Constructors are declared as public member function.
Constructors are automatically invoked when an object of class is created.
Constructor has same name as the class name.
Constructors don‟t have any return type.
Constructors can have default arguments.
Constructors cannot be inherited, though a derived class can call the base class
constructor.
Constructors cannot be virtual
Constructors cannot refer to their addresses.
Constructors can implicitly call new and delete operators when memory
allocation is required.
Constructors can be defined either inside the class definition or outside class
definition. If constructors are defined outside class definition, then they can be defined
using class name and scope resolution:: operator.
18
Example: To define Constructor inside the class.
class MyNumber
{
int n;
public:
MyNumber( ) //Constructor defined inside the class
{
n=10;
}
};
class MyNumber
{
int n; public:
MyNumber( ); //Constructor declared
};
MyNumber :: MyNumber ( ) //Constructor Defined outside the class
{
n=10;
}
When a class contains a constructor, objects of the class will be initialized automatically.
Ex. MyNumber Obj1;
Here Obj1 invokes constructor and initializes the data members of class MyNumber. If
constructor is not defined in a class, C++ compiler generates a default constructor.
1. Default Constructor:
The constructor that accepts no arguments is called as Default Constructor.
#include<iostream.h>
class MyNumber
{
int n; public:
19
MyNumber( ) //Default Constructor
{
n = 0;
}
};
int main( )
{
MyNumber Obj1;
return 0;
}
MyNumber Obj1 invokes Default constructor and initializes data member n to 0(zero).
2. Parameterized Constructors:
The constructor that accepts arguments is called as Parameterized constructor. These
arguments initialize an object, when it is created. The constructors can be called
explicitly or implicitly.
If more than one constructor is defined in a class, it is called as Constructor
Overloading.
#include<iostream.h> class
MyNumber
{
int n; public:
MyNumber(int x ) //Parameterized Constructor
{
n = x;
}
};
int main( )
{
MyNumber Obj1 = MyNumber(10);// Explicit
call MyNumber Obj2(20);// Implicit call
}
MyNumber Obj1 & MyNumber Obj2 invokes parameterized constructor and initializes
data member n to 10 & 20 respectively.
20
3. Copy Constructor:
A constructor that initializes an object using another object of the same class is called
as copy constructor. It takes a reference of object of the same class as its argument. It
copies data from one object to other by copying every member of an object with the
member of object passed as argument.
int main( )
{
MyNumber Obj1(10),
Obj2(Obj1);
return 0;
}
MyNumber Obj2(Obj1) defines the obj2 and at the same time initializes it to values of Obj1.
4. Dynamic Constructor:
The constructor can be used to allocate memory while creating objects. Memory can be
allocated using new operator. Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects.
#include<iostream.h>
#include<string.h>
class MyString
{
21
char *Str;
int len;
public:
MyString()
{
len=0;
Str=new char [len+1];
}
len=strlen(S);
Str=new char [len+1];
strcpy(Str, S);
}
void Concatenate(MyString &S1, MyString &S2)
{
len=S1.len+S2.len;
delete Str;
Str=new char[len+1];
strcpy(Str, S1.Str);
strcat(Str, S2.Str);
cout<<“String =”<<Str;
}
};
int main( )
{
MyString Obj1(“Artificial”), Obj2(“Intelligence”), Obj3;
Obj3.Concatenate(Obj1, Obj2);
return 0;
}
#include<iostream.h> class
MyNumber
{
int m, n; public:
MyNumber(int x, int y=20 )
22
{
m = x; n=y;
}
};
int main( )
{
MyNumber Obj1(10);
}
MyNumber Obj1 invokes constructor with default arguments and assigns the value
10 to the variable x and 20 to variable y.
Class objects can be initialized dynamically i.e. initial value of an object can be provided
during run time. Dynamic initialization is used to provide various initialization formats,
using overloaded constructors.
23
2.2.2 Destructor:
Destructor is a member function that destroys an object which has been created by
constructor. If new operator is used to allocate memory in the constructors, delete operator
is used to free memory in the destructor. Destructor can clean up the storage which is no
longer accessible.
A destructor is invoked implicitly when the object goes out of scope like:
a. The function ends
b. The program ends
c. A block containing local variables ends
d. A delete operator is called
Characteristics of Destructor:
Destructors have same name as the class name preceded by a tilde (~).
Destructor doesn‟t take any argument and doesn‟t return any value.
};
int main( )
{
MyNumber Obj1;
{
MyNumber Obj2;
} //Destructor Obj2 called
return 0; //Destructor Obj1 called
}
24
Practical Assignment
SET A:
1. Write a C++ program to define a class „Triangle‟ with private data members base and height.
Create and initialize the object using parameterized constructor. Write a destructor to
destroy the created object. Display appropriate message when object will get created
and destroyed.
2. Write a C++ program to define a class „ComplexNumber‟ with private data members real
and imaginary. Create and initialize the object using parameterized constructor. Write a
member function to calculate and display addition of two ComplexNumber.
3. Write a C++ program to define a class „Student‟ with private data members name, grade, and
age. Write a parameterized constructor with default values for grade as 'P'. Write member
functions to display student details.
SET B:
1. Write a C++ Program to define a class „Date‟ with private data members dd,mm,yyyy. Use
parameterized constructor to initialize the date. Write a member function to validate the
date.
2. Write a C++ program to create a class „MyPoint‟ with two integer data members as x & y.
Define copy constructor to copy one object to another.
25
allocated memory. Write member functions to accept and display the string.
2. Write a C++ program to define a class „Employee‟ with a static data member count that
keeps track of the number of Employee objects created. Use a constructor to increment the
count each time a new object is created and a destructor to decrement the count when an
object is destroyed. Display the Employee count in the constructor and destructor.
3. Write a C++ program to define a class „BankAccount‟ with private data members
accNumber, accHolderName and balance. Write a parameterized constructor to initialize the
object and write member functions to deposit money, withdraw money, and display the
account details.
4. Write a C++ program to define a class „Student‟ with data members Rollno, Name,
No_of_sub, Marks of each subject (Number of subjects varies for each student). Write a
parameterized constructor to initialize the object. Display the details of student with
percentage and class obtained.
Assignment Evaluation
___________________________________________________________________________
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]
26
c. Inline, Static and Constant function
To learn about:
• Inline function.
• Static function.
• Constant function
Reading
You should read following topics before starting this exercise:
• Classes and Objects
• Member Functions
• Characteristics of Inline function
• Characteristics of Static function
• Characteristics of Constant function
Ready References
When the program executes the function call instruction, the CPU stores the memory address
of the instruction following the function call, copies the arguments of the function on the
stack and finally transfers control to the specified function. The CPU then executes the
function code, stores the function return value in a predefined memory location/register and
returns control to the calling function.
This can become overhead if the execution time of function is less than the switching time
from the caller function to called function. For functions that are large and/or perform
complex tasks, the overhead of the function call is usually insignificant compared to the
amount of time the function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time needed to actually
execute the function‟s code. This overhead occurs for small functions because execution time
of small function is less than the switching time.
C++ provides an inline function feature to reduce the function call overhead. It also saves
overhead of arguments push/pop on the stack, while function calling. Inline function is a
function that is expanded in line when it is called. If a function is Inline, the compiler places a
copy of the code of that function at each point where the function is called at compile time
and may make the program execution faster.
To inline a function, place the keyword inline before the function name and define the
27
function before any calls are made to the function. The compiler can ignore the inline
qualifier, in case defined function is more than a line.
Syntax:
inline return-type function-name (argument list)
{
//Function Body
}
#include <iostream.h>
inline int square(int x)
{
return (x*x);
}
int main()
{
cout<< "Square (2): " <<square(2) <<endl;
cout<< "Square (3): " <<square(3) <<endl;
return 0;
}
Output:
Square (2): 4
Square (3): 9
28
Static data members are associated with the class itself rather than with any class object,
hence they are also known as class variables.
Output:
Value of num is : 10
Constant member functions are those functions that are denied permission to change the values of
the data members of their class. To make a member function constant, the keyword const is
29
appended to the function prototype and also to the function definition header. It is recommended
to use const keyword so that accidental changes to object are avoided.
A const member function can be called by any type of object. Non-const functions can be called by
non-const objects only.
#include <iostream.h>
class Demo
{
int x;
public:
void set_data(int a)
{ x = a; }
Practical Assignment
SET A:
1. Write a C++ program that defines an inline function to convert a temperature from Celsius
to Fahrenheit.
2. Write a C++ program that defines an inline function to compute the perimeter of a rectangle
given its length and width. Use this function to compute and display the perimeter for
several rectangles.
3. Write a C++ program that defines a class „Employee‟ with private static data members for
the company name and a static member function to set and get this static data member.
30
4. Write a C++ program that defines a class „Rectangle‟ with private data members width and
height. Write a constant member function to calculate and return the area of the rectangle.
SET B:
1. Write a C++ program that defines an inline function to find the maximum value in an array
of integers. Use this function to find and display the maximum value from multiple arrays.
2. Write a C++ program that defines a class „TConverter‟ with static member functions to
convert temperatures between Celsius and Fahrenheit. Use these functions to perform and
display conversions for various temperatures.
3. Write a C++ program that defines a class „Array‟ with a private data member for an array of
integers. Write a constant member function to calculate and return the sum of the array
elements.
Practice Programs:
1. Write a C++ program that defines an inline function to print a greeting message.
2. Write a C++ program that defines an inline function to print cube of given number.
3. Write a C++ program that defines a class „Constants‟ with static member functions to get
mathematical constant PI. Use this function to display the constants.
4. Write a C++ program that defines an inline function to calculate the area of a circle. The
function should have a default argument for the radius. Use this function to calculate and
display the area for both default and user-specified radius.
5. Write a C++ program that defines a class „Triangle‟ with inline member functions to
calculate the area and perimeter of triangle. Use these inline functions to compute and
display the area and perimeter for different Triangle objects.
31
Assignment Evaluation
__________________________________________________________________________
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]
32
d. Function Overloading and Operator Overloading
To Learn about:
Function Overloading
Operator Overloading
Reading:
You should read following topics before starting this exercise:
Function
Function Overloading
Operator Overloading
Ready References:
2.4 Polymorphism:
Function Overloading:
Same function name is used to create a function that perform variety of different tasks is
called as Function Overloading.
A family of functions can be designed with same function name but with different argument
list. The function performs different operations depending on the argument list in the function call.
The appropriate function to be invoked is determined by checking the number and type of
arguments.
33
Example 1: C++ program to find area of triangle, circle, and rectangle using function
overloading.
#include<iostream.h>
float area(float r)
{
return(3.14*r*r);
}
int main()
{
int m,n;
float l,a;
cout<<"CIRCLE:\n";
cout<<"Enter the Radius: ";
cin>>l;
a=area(l);
disp(a);
cout<<"\n\nTRIANGLE\n:";
cout<<"Enter the Base and Height:";
cin>>l>>m;
a=area(l,m);
disp(a);
cout<<"\n\nRECTANGLE:\n";
cout<<"Enter the Length and Breadth:";
cin>>m>>n;
a=area(m,n);
disp(a);
return 0;
}
34
Overloaded operator is used to perform operation on user-defined data type. Although semantics of
an operator can be extended, but cannot change its syntax, the grammatical rules that govern its use
such as the number of operands, precedence and associativity.
For example '+' operator can be overloaded to perform addition on various data types, like for
integer, float etc.
Operator overloading is achieved using the operator function. The operator function is
created using operator keyword.
35
void accept(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}
void operator -()
{
x=-x;
y=-y;
}
};
int main()
{
Numbers N;
N.accept(10,20);
N.display();
-N;
cout<<"\nAfter unary minus handled variable are:"<<"\n";
N.display();
return(0);
}
#include<iostream.h>
class Numbers
{
int x;
int y;
public:
void accept(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}
friend void operator -(Numbers &Obj)
{
36
Obj.x=-Obj.x;
Obj.y=-Obj.y;
}
};
int main()
{
Numbers N;
N.accept(10,20);
N.display();
operator –(N);
cout<<"\nAfter unary minus handled variable are:"<<"\n";
N.display();
return(0);
}
37
Numbers operator +(Numbers Obj)
{
Numbers temp;
temp.x=x+Obj.x;
return temp;
}
};
int main()
{
Numbers N1,N2,N3;
N1.accept(100);
N2.accept(200);
cout<<"\nFirst number:";
N1.display();
cout<<"\nSecond number:";
N2.display();
cout<<"\nOperations:\n\n";
cout<<"\nAddition:";
N3=N1+N2;
N3.display();
return(0);
}
#include<iostream.h>
class Numbers
{
int x;
public:
void accept(int a)
{
x=a;
}
void display()
{
cout<<"x="<<x<<"\n";
}
friend Numbers operator +(Numbers Obj1,Numbers Obj2)
{
Numbers temp;
temp.x=Obj1.x+Obj2.x;
return temp;
}
};
int main()
{
Numbers N1,N2,N3;
38
N1.accept(100);
N2.accept(200);
cout<<"\nFirst number:";
N1.display();
cout<<"\nSecond number:";
N2.display();
cout<<"\nOperations:\n\n";
cout<<"\nAddition using friend function:";
N3=operator+(N1,N2);
N3.display();
return(0);
}
39
cout<< "Input";
cin>>N; //invokes operator >>( ) function
cout<<"Output";
cout<<N; //invokes operator <<( ) function
return 0;
}
Set A:
1. Write a C++ program to find area of circle and area of rectangle. (Use function
overloading).
2. Write a C++ program to overload function swap() that can swap two integers or two
doubles. Use reference parameters to perform the swap. (Use function overloading)
3. Write a C++ program to create a class Number with two integer data members. Write
necessary member functions to overload the operator unary pre and post increment „++‟.
4. Write a C++ program to create a class Max. Write member functions to accept and display
an integer number. Overload binary „<‟ operator to compare the objects of a class.
5. Write a C++ program to create a class MyString, with data member character pointer. Write
member functions to accept and display a string. Overload „+‟ operator to concatenate two
strings. (Use new Operator)
Set B:
1. Write a C++ program to create a class Person with data members Person_name,
Mobile_number, Person_addr, City. Write necessary member functions for the following
using function overloading:
i. Search the mobile number of given person.
ii. Search the person name of given mobile number.
iii. Search all person details of given city.
2. Write C++ program to find volume of cube, cylinder and rectangle using function
overloading.
3. Create a class MyString which contains a character pointer (using new operator). Write a
C++ program to overload followingoperators:
i. < To compare length of twostrings
ii. != To check equality of twostrings
iii. + To concatenate twostrings
4. Write a C++ program to create a class Time with data members hours, minutes and seconds.
Use operator overloading to perform the following:
i. != To check whether two Times are equal or not.
ii. >> To accept the time.
iii. << To display the time.
40
Set C:
1. Case Study: Financial Application
Question: Develop a Financial Application that deals with complex monetary operations.
Create a Money class to represent monetary values and perform various operations on these
values.
Define the Class “Money”:
- Attributes: Rupees and Paise
- Methods: Constructor and methods for operator overloading
Practice Programs:
1. Write a C++ program to add 2 integer numbers and to add 2 float Numbers. (Use function
overloading)
2. Write a C++ program to find volume of cylinder, cone and sphere. (Use function
overloading).
3. Write a C++ program to create a class Weight with data member kilogram and gram. Use
operator overloading to perform following functions:
i. To accept weight
ii. To display weight.
iii. To overload += operator to add two weights.
iv. To overload == operator to check equality of two weights.
Assignment Evaluation
___________________________________________________________________________
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]
41
Assignment No. 3: Inheritance
To learn about:
• To know about inheritance.
• Types of inheritance.
• To know about virtual base class.
• To know about abstract class.
• To know about virtual and pure virtual functions.
Reading
You should read following topics before starting this exercise:
• concept of inheritance
• types of inheritance
• polymorphism – run time and compile time
• virtual inheritance
• Concept of Overriding - virtual functions and pure virtual functions
Ready References
3.1 Inheritance
Inheritance is the process of creating new classes from an existing class. The existing class is
known as base class and the newly created class called as a derived class.
Defining the derived class: class derived_class_name:
visibility_mode base_class_name
{
--------
-------- };
Example: class ABC
{
----------
---------
};
class XYZ: private ABC
{
--------- ---------- };
Following table shows how the visibility of base class members undergoes modifications in all
three types of derivation.
42
Base class Visibility Derived class visibility
Public derivation Private Derivation Protected
Derivation
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected
Types of Inheritance
1. Single inheritance
If the derived class inherits from a single parent, the inheritance is said to be single inheritance.
Example: same as above.
2. Multiple inheritance
Multiple inheritance is the process of creating a new class from more than one base classes.
Example:
class ABC
{
----------
---------
};
class XYZ
{
----------
};
class test: public XYZ, public ABC
{
----------
---------
};
3. Multilevel inheritance
One class derived from a base class, is further used as a base class of some other class. Therefore,
the class which provides link between two classes is known as intermediate base class.
class ABC
{
----------
---------
};
class XYZ: private ABC
{
---------
---------
};
43
class LMN: public XYZ
{
------------
----------
};
4. Hierarchical Inheritance
This is the process where many derived classes share the properties of base class.
Example:
A student shows a hierarchy as Arts, medical or engineering students. The medical is again has a
hierarchy as medicine, surgery, radiology, gynaec, etc.
5. Hybrid Inheritance
It is referred as multiple base class of a derived class having the same base class.
Example: case of multilevel inheritance where student, test and result are three classes. But suppose
someone or say authority wants that some weightage should be given for sports to finalize the result.
In this, child can inherit the properties via two direct base classes or it may inherit directly.
The duplication of inherited members due to these multiple paths can be avoided by making
common base class as virtual base class while declaring the direct or intermediate base classes.
Example:
Consider, the „child‟ has two direct base classes parent1 and parent2 which themselves have a
common base class „grandparent‟.
class grand
{
--------------
--------------
};
class p1: virtual public grand
{
---------------
---------------
};
class p2: virtual public grand
{
---------------
-----------------
};
class child: public p1, public p2
{
---------
---------- // only one copy of grand will be inherited.
};
44
3.4 Abstract Classes
Destructors in class hierarchy are invoked in the reverse order of the constructor‟s invocation. The
constructor of that class whose constructor was executed last, will be executed first whenever the
object goes out of the scope. If destructors are missing in any class in the hierarchy of classes; that
class‟s destructor is not invoked.
It is a member function that is declared within a base class and redefined by a derived class. They
cannot be static members. Prototype of base class version of virtual function and all the derived
class version must be identical. They are accesses by using object pointers. We cannot use a
pointer to a derived class to access an object of the base type.
45
Example 1:
class base
{
public:
void disp()
{
cout<<”base”;
}
virtual void show()
{
cout<< “showbase”;
}
};
class der : public base
{
public:
void disp()
{
cout<<”derived”;
}
Void show()
{
cout<<”show derived”;
}
};
void main ()
{
base ob1;
der ob2;
cout<<”bptr points to base”;
bptr=&ob1;
bptr->disp(); // call base version
bptr->show(); // call base version
cout<<”bptr points to derived”;
bptr=&ob2;
bptr->disp(); // call to base
bptr->show(); // call to derived
}
46
Output:
bptr points to base
base
showbase
bptr points to derived
base
derived
A pure virtual function is a virtual function that has no definition within the base class.
When a virtual function is made pure, any derived class must provide its own definition. A class
containing pure virtual function is an abstract class.
Practical Assignment
SET A
1. Create base class called shape. Use this class to store two double type values that could be used
to compute the area of figures. Derive three specific classes called triangle, circle and rectangle
from the base shape. Add to the base class, a member function get_data() to initialize base class
data members and display_area() to compute and display area. Make display_area() as a virtual
function.(Hint: **use default value for one parameter while accepting values for shape circle.)
3. Create a multiple inheritance scenario in C++ to represent a system where Person class,
Employee class, and Customer class are inherited by a vendor class.
4. Write a program in C++ to read the following information from the keyboard in which the base
class consists of employee name, code and designation. The derived class Manager which
contains the data members namely, year of experience and salary. Display the whole
information on the screen.
SET B
1. Create a class hierarchy to represent different types of shapes. Use virtual functions to allow
dynamic binding and display the shape's details. Implement a base class Shape with derived
classes Circle and Rectangle.
47
2. Design a system where different types of animals make different sounds. Use polymorphism
to handle various animal types using a base class Animal and derived classes Dog, Cat, and
Cow.
3. Create a C++ program demonstrating hybrid inheritance using a real-life example of a
University System with classes Person, Student, Employee, and TeachingAssistant.
Implement constructors, accept input, and display details, showing how attributes and
methods are inherited and combined in the TeachingAssistant class.
SET C
Case Study 1: Library Management System
Question: Develop a library management system using C++ with inheritance. Implement a base
class LibraryItem, and derived classes Book and Magazine.
Question: Implement an employee payroll system using C++ with inheritance. Create a base class
Employee and derived classes FullTimeEmployee and PartTime
Assignment Evaluation
48
Assignment 4: a. Exception Handling
4.1 Introduction to Exception
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.
• The try statement allows you to define a block of code to be tested for errors while it is
being executed.
• The throw keyword throws an exception when a problem is detected, which lets us create a
custom error.
• The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
49
// catch block
}
Throwing Exceptions
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.
Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch
Example program 1:
Write a C++ Program Containing a Possible Exception. Use a Try Block to throw it and a Catch
Block to Handle it Properly.
#include <iostream>
using namespace std;
int main()
{
int x = -1;
cout<<"Before try\n";
try
{
cout<<"Inside try\n";
if (x < 0)
{
throw x;
cout<<"After throw(Never executed)\n";
}
}
catch(int x)
{
cout<<"Exception Caught\n";
}
50
cout<<"After catch(Will be executed)\n";
return 0;
}
Output:
Before try
Inside try
Exception Caught
After catch(Will be executed)
Example Program 2:
Write a C++ program to demonstrate the catching of all exceptions.
#include<iostream.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw „x‟;
}
catch(int x)
{
Cout<<”Catch a integer and that integer is:”<<x;
}
catch(char x)
{
Cout<<”Catch a character and that character is:”<<x;
}
void main()
{
cout<<"Testing multiple catches\n:";
test(10);
test(0);
51
}
Output:
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x
SET A:
1. Write a program to handle DIVIDE BY ZERO exception.
2. Accept two integers numbers say x and y. If x > y , perform subtraction otherwise throw an
exception.
3. Write a program to throw an exception “INVALID AGE” , if the age is less than 0 and greater
than 100.
SET B:
1. Write a program to accept a number from the user, if number is zero then throw user defined
exception “Number is 0” otherwise check whether no is prime or not (Use static keyword).
2. Create User defined exception to check the following conditions and throw the exception
if the criterion does not meet.
a. User has age between 18 and 55
b. User stays has income between Rs. 50,000 – Rs. 1,00,000 per month
c. User stays in Pune/ Mumbai/ Bangalore / Chennai
d. User has 4-wheeler
Accept age, Income, City, Vehicle from the user and check for the conditions mentioned
above. If any of the condition not met then throw the exception.
a) 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 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 instantiates the book and tape classes, allows user to enter data and displays
the data members. If an exception is caught, replace all the data member values with zero values.
b) A book shop maintains the inventory of books that are being sold at the shop. The list includes
52
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 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 books with suitable member functions and Constructors. Use
new operator in constructors to allocate memory space required. Implement C++ program for the
system.
53
b. Templates
4.2 Introduction:
Templates are powerful features of C++ which allows you to write generic programs. 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. In simple terms, we can create a single function or a class to work
with different data types using templates. Templates are often used in larger code base for
the purpose of code reusability and flexibility of the programs. The concept of templates can
be used in two different ways:
FunctionTemplates
ClassTemplates
54
{
return (num1 + num2);
}
int main()
{
int result1;
double result2;
// calling with int parameters result1 = add(2, 3);
cout << "2 + 3 = " << result1 << endl;
return 0;
}
Output:
2+3=5
2.2 + 3.3 = 5.5
... .....
};
55
T is a generic name for a data type which will be specified when a class is instantiated. we
candefine more than one generic data type by using a comma-separated list.
};
56
}
Output:
Values of a and b are: 5, 6.5
Practice programs:
1. Write a C++ program to swap two integer values and two float values by using
functiontemplate.
Set A:
1. Write a C++ template program to accept array elements of type integers &
characters.Reverse an array of both types.
2. Write a C++ program to find maximum & minimum of two integer numbers and two
float numbers by using function template.
3. Write a C++ template program to sort the array elements of type integer,
float andcharacter.
Set B:
1. Write a C++ program to define class template for calculating the square of given
numberswith different datatypes.
2. Write C++ template program to find the area of circle & rectangle with different
datatypes.
3. Write a template to represent a generic vector. Include member functions to
perform the following tasks:
i. To create the vector.
ii. To modify the value of a given element.
iii. To multiply the vector by a scalar value.
iv. To display the vector in the form (10,20,30,…..)
Assignment Evaluation
57