KEMBAR78
Final OOPs and C++ Lab Book | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
57 views57 pages

Final OOPs and C++ Lab Book

Uploaded by

ramsah3757
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views57 pages

Final OOPs and C++ Lab Book

Uploaded by

ramsah3757
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Savitribai Phule Pune University

F. Y. B. S. c. (AI & ML) Semester-I


(CBCS 2024 Pattern)

Practical based on AIML-101-T


(Object Oriented concepts and Programming using C++)

AIML-102-P: Lab Book

Roll No.: Division: Seat No.:

Student Name:

College Name:

Academic Year:
CERTIFICATE

This is to certify that Mr./Ms _________________________________________


Seat number ________ of F.Y.B.Sc. (AI & ML) Sem-I has successfully completed Laboratory
Course (AIML-102-P Practical based on AIML-101-T) in the year_________________.
He / She has scored mark ______out of 10 (for Labbook).

Subject Teacher H.O.D./Coordinator

Internal Examiner External Examiner

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

Assistant Professor, ATSS College of Business Studies and Computer Application,


Chinchwad

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

1. About the workbook:

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.

2. The objectives of Labook:


 To define the scope of the course clearly, ensuring all relevant topics and skills are covered.
 To bring uniformity in the conduction and implementation of practicals across all colleges
affiliated with SPPU.
 To facilitate continuous assessment of the course and the students' performance.
 To provide a ready reference for students during practical implementations, enhancing their
understanding and application of concepts.
 To offer students multiple practice options, enabling them to gain confidence and
proficiency before examinations.
 To cater to the needs of both slow and fast learners by providing tailored practice
assignments that address their specific learning pace and requirements.

3. Instructions to the Students:


Please read the following instructions carefully and follow them during practical.
 Students must bring this lab workbook to every practical session in the computer lab.
 Before each session, students should prepare for the assigned tasks by reviewing the
relevant material provided in the ready reference section of the labbook.
 Solve the problems assigned by the instructor during lab time and get them verified.
Additional time in the lab or at home may be required to complete all labbook
assignments.
 Students will be assessed for each assignment on a scale from 0 to5.

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

Sr. Assignment Name Marks Teacher‟s


No. (out of 10) Sign

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

b. Conduct Quiz at the time of submission

a. Total out of 10

b. Total out of 5

b. Total (out of 15) (a+b)

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.

Procedural programming is about writing procedures or functions that perform operations


on the data, while object-oriented programming is about creating objects that contain both
data and functions.
Object-oriented programming has several following advantages over procedural
programming:
 OOP is faster and easier to execute.
 OOP provides a clear structure for the programs.
 OOP makes the code easier to maintain, modify and debug.
 OOP makes it possible to create full reusable applications with less code
and shorter development time.
 OOP makes development and maintenance easier if code grows as project size grows.
 OOP provide data hiding
 OOP provide ability to simulate real-world event much more effectively.

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;
}

1.1 Fundamental components in C++ programs:


• Comments: // My first C++ program
In above C++ program first line with double slash symbol indicate single line comment and to
indicate multiline comment programmer can enclose multiple lines in /* */ which means these lines
inserted by the programmer has no effect on the behavior of the program. Programmers use
comment to include short explanations or observations about program.

• Header files: #include <iostream.h>


Lines beginning with „#‟ are directives which are read and interpreted by preprocessor before the
compilation of the C++ program begins. In above C++ program directive #include <iostream.h>,
instructs the preprocessor to include header file iostream, which allows to add the contents of the
iostream.h file to the program to perform standard input and output operations, such as accepting
input through keyboard and writing the output of program on screen.

• Main function: int main ()


The function named main is a special function in all C++ programs; it is the function which called
by operating system automatically when C++ program run. The execution of all C++ programs
begins with the main function, regardless of where the function is actually located within the code.
Proper way of writing the main function in C++ is to use int return type for main function. C++
standards and specifications mention that the main function should always return integer value
which can be „0‟ or „1‟ where „0‟ is the standard for “successful execution of the program”.

• 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.

 C++ Input and Output Operators:


In C++ cout is a predefined object which is an instance of ostream class. The cout object is
connected to the standard output device, which usually is the display screen. The cout is used in
conjunction with output operator "<<" ("put to"), also known as stream insertion operator to direct a
value to standard output i.e. to display output on the screen.
cin is a predefined object which is an instance of istream class. The cin object is connected to the
standard input device, which usually is the keyboard. The cin is used in conjunction with input
operator ">>" ("get from"), also known as stream extraction operator to read a value from standard
input i.e. to accept input from keyboard.

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);

cout << "Length: " << rect.getLength() << endl;

cout << "Width: " << rect.getWidth() << endl;

cout << "Area: " << rect.area() << endl;

return 0;

1.5 Member function definition outside the class definition:


If the member function is defined outside the class, then we have to use the scope resolution
operator „::‟ along with class name and function name. Function name in the function header
is preceded by the class name and the scope resolution operator (: :).

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.

1.6 Static data members:


Static data members are class members that are declared using the static keyword. The
normal variable is created when the function is called and its scope is limited, while the
static variable is created once and destroyed at the end of the program. These variables
are visible within the class but its lifetime is till the program ends. There is only one
copy of the static data member in the class, even if there are many class objects. This is
because all the objects share the static data member. To hold the count of objects created

11
for a class, static data members are used.

1.7 Static member functions:


Like static data member, we can also have static member functions. A static member
function can only access other static variables or functions present in the same class. To
create a static member function we need to use the static keyword while declaring the
function.
Practice Set
1. Write a C++ program to check whether a given number is odd or even.
2. Write a C++ program to convert decimal number into binary number.
3. Write a C++ program to demonstrate how to access and print the value of private
member of a class using public member function.
4. Write a C++ program to display first „n‟ numbers of Fibonacci series.
Set A
1. Write a C++ program to check whether a given number is Armstrong or not.
2. Write a C++ program to generate multiplication table.
3. Write a C++ program that displays mixed data types and arithmetic operations.
4. Write a C++ Program to print result of the student as per the following criteria

Percentage Class Percentage Class


100 to 70 Distinction 50 to 40 Pass class
70 to 60 First class Below 40 Fail
60 to 50 Second class

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

0: Not Done [ ] 1: Incomplete [ ] 2.Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor Date of Completion ____/____/____

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:

2.1 Array of objects:

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.

2.1.1 Objects as a function argument:

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.

2.1.2 Function returning objects:


As entire object is passed as an argument, similarly an object is returned from the function. Entire
object can be returned from function by specifying its return type as class name just like primary
data-types. An object can be returned by a function using the return keyword.
Set A:
1. Write a C++ program to create a class Product with data members Product_id,
Product_Name, Product_Qty, Product_Price. Write member functions to accept and display
information of 3 products.

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

Case Study 2: Online Retail Store


Question: Develop an Online Retail Store to manage collection of product information.
Each product has data members as Product_id, Product_name, Product_Price,

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 [ ]

Signature of Teacher / Instructor Date of Completion __ / __ / ______

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;
}
};

Example: To define Constructor outside the class.

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.

2.2.1 Types of Constructors:

1. Default Constructor:
The constructor that accepts no arguments is called as Default Constructor.

Example: To illustrate the use of 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.

Example: To illustrate the use of Parameterized Constructor.

#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.

Example: To illustrate the use of Copy Constructor.


#include<iostream.h>
class Number
{
int n; public:
MyNumber (int x)
{
n = x;
}
MyNumber (MyNumber &N) //Copy Constructor
{
n= N.n;
}
};

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.

Example: To illustrate the use of Dynamic Constructor.

#include<iostream.h>
#include<string.h>
class MyString
{

21
char *Str;
int len;
public:
MyString()
{
len=0;
Str=new char [len+1];
}

MyString (char *S)


{

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;
}

Constructors with default arguments:

It is possible to define constructors with default arguments.

Example: To illustrate the use of Constructors with default arguments.

#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.

Dynamic initialization of Objects:

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.

Example: To illustrate the use of Dynamic initialization of Constructor


#include<iostream.h>
class MyNumber
{
int n; public:
MyNumber(int x)
{
n = x;
}
void display()
{
cout<<"n = " <<n;
}
};
int main( )
{
int a;
cout<<"\n Enter the valuea:";
cin>>a;
MyNumber
Obj(a);
Obj.display();
return 0;
}

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.

Example: To illustrate the use of Destructor.


#include<iostream.h>
class MyNumber
{
public:
MyNumber ( )
{
cout<<”\n Constructor called”;
}
~MyNumber ( )
{
cout<<”\n Destructor called”;
}

};
int main( )
{
MyNumber Obj1;
{
MyNumber Obj2;
} //Destructor Obj2 called
return 0; //Destructor Obj1 called
}

Note: Objects are destroyed in the reverse order of creation.

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.

SET C: Case Study


1. Consider a graphics application that deals with rendering images. The application uses a
class Image to manage the loading, manipulation, and display of images. The Image class
must handle resources like memory buffers for pixel data, file handles, or GPU resources.

2. Imagine a software system that interacts with a database. A class DatabaseConnection is


used to establish and close the database connection.
Practice Programs:
1. Write a C++ program to define a class „String‟ that uses dynamic memory allocation to store
a string. Write a dynamic constructor to initialize the string and a destructor to release the

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 [ ]

Signature of Teacher / Instructor Date of Completion __ / __ / ______

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

2.3 Inline Function:

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
}

Example: C++ program to illustrate use of inline function.

#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

2.3.1 Static data members and Static member functions:

Static data members:


Static data members are class members that are declared using the static keyword. The normal
variable is created when the function is called and its scope is limited, while the static variable
is created once and destroyed at the end of the program. These variables are visible within the
class but its lifetime is till the program ends. There is only one copy of the static data member
in the class, even if there are many class objects. This is because all the objects share the static
data member. To hold the count of objects created for a class, static data members are used.
The static data member is always initialized to zero when the first class object is created.
While defining a static variable, some initial value can also be initialized to the variable. Type
and scope of each static member variable must be defined outside the class definition using
scope resolution operator. This is necessary because the static data members are stored
separately rather than as a part of an object.

28
Static data members are associated with the class itself rather than with any class object,
hence they are also known as class variables.

Static member functions:


Like static data member, we can also have static member functions. A static member function
can only access other static variables or functions present in the same class. To create a static
member function, we need to use the static keyword while declaring the function.
Since static member variables are class properties and not object properties, to access them
we need to use the class name instead of the object name. A static member function can be
called even if no objects of the class exist and the static functions are accessed using class
name and the scope resolution operator ::. You could use a static member function to
determine whether some objects of the class have been created or not.
Example: C++ program to illustrate use of static data member and static member
function.
#include <iostream.h>
class StaticDemo
{
private:
static int num; //declaration of static data member
public:
static void Display() //static member function definition
{
cout<<"Value of num is : "<<num<<endl;//accessing static data member
}
};
int StaticDemo :: num=10;
//static data member definition and initialization outside class
int main()
{
StaticDemo::Display();//call to static member function
return 0;
}

Output:
Value of num is : 10

2.3.2 Constant functions:

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.

Example: C++ program to illustrate use of constant function.

#include <iostream.h>
class Demo
{
int x;

public:
void set_data(int a)
{ x = a; }

// constant member function


int get_data() const
{
// Error while attempting to modify the data member
++x;
return x;
}
};
main()
{
Demo d;
d.set_data(10);
cout << endl << d.get_data();
return 0;
}

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.

SET C: Case Study


1. Consider a scientific computing application that performs millions of small mathematical
operations, such as calculating the square of a number, square root of a number etc.
2. Develop a math library that includes several utility functions, such as calculating the
factorial of a number or checking if a number is prime. These functions do not depend on
any instance-specific data and should be callable without creating an object of the class.

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 [ ]

Signature of Teacher / Instructor Date of Completion __ / __ / ______

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:

Polymorphism means „One name, multiple forms‟.

2.4.1 Compile time Polymorphism:


Compiler selects appropriate function for a particular call at compile time is called as
Compile time Polymorphism. It is also called as early binding or static binding or static linking.
Compile time Polymorphism is achieved by using function overloading and operator overloading.

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);
}

float area(float b,int h)


{
return(0.5*b*h);
}

int area(int l,int b)


{
return(l*b);
}
void disp(float m)
{
cout<<"\nArea: "<<m;
}

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;
}

2.4.2 Operator Overloading:

In Operator Overloading, an operator is overloaded to give user defined meaning to it.

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.

Syntax of operator function:


returntype classname :: operator Op (argument List)
{
//Function Body
}
where,
returntype is the type of value returned by the specified operation.
op is the operator being overloaded. op is preceded by the keyword operator. „operator op‟ is
the function name.
The argument list will depend on whether the operator is unary or binary and whether the
function is a member function or friend function.

The operator function can be either member function or friend function.


 A friend function will have one argument for unary operators and two for binary operators.
 A member function has no arguments for unary operators and only one for binary operators
because the object used to invoke the member function is passed implicitly and therefore is
available for member function.
Restrictions on Operator overloading while implementing operator overloading:
1. Precedence and Associativity of an operator cannot be changed.
2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains
binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
5. There are few operators in C++ that cannot be overloaded such as
 ternary operator ?:,
 sizeof,
 scope resolution operator ::
 membership operators . and .* .

Overloading Unary operators:


Unary operators are Increment, Decrement and unary minus which can be overloaded.
Example 2: To overload the operator unary minus- to negate the numbers.
#include<iostream.h>
class Numbers
{
int x;
int y;
public:

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);
}

Overloading Unary operators using friend function:


Example 3: To overload operator unary minus - to negate the numbers using friend function.

#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);
}

Overloading increment operator:


The increment operator ++ is used in two ways: pre-increment (++d) and post-increment(d++).
To distinguish between pre and post increment operator overloading, dummy parameter of type int
in the function heading of the post-increment operator function is used. Decrement operator can be
overloaded similarly.
void operator++()
{
++x;
++y;
}
void operator++(int)
{
x++;
y++;
}

Overloading Binary operators:


Arithmetic operators (+, - , * ,/) are overloaded to perform arithmetic operation on user-defined data
type.
Example 4: To Overload Binary „+‟ operator using member function
#include<iostream.h>
class Numbers
{
int x;
public:
void accept(int a)
{
x=a;
}
void display()
{
cout<<"x="<<x<<"\n";
}

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);
}

Example 5: To Overload Binary operator „+‟ using friend function.

#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);
}

Overloading insertion and extraction operators:


Overloading insertion(<<) operator and extraction (>>) operator is used to input and output objects
using stream class library in the similar way as built in data types.
<< operator is overloaded with ostream class object cout to print primitive type value to the screen.
Similarly << operator is overloaded in class to print user-defined type to screen.
>> operator is overloaded with istream class object cin to read primitive type values from the user.
Similarly >> operator is overloaded in class to read user-defined type value.

Example 6: To Overload << & >> operator.


#include<iostream.h>
#include<fstream.h>
class Numbers
{
int x;
public:
friend ostream& operator <<(ostream &,Numbers &);
friend istream& operator >>(istream &,Numbers &);
};
ostream & operator <<(ostream &out,Numbers &d)
{
out<<"\nValue of x:"<<d.x;
return out;
}
istream & operator >>(istream &in,Numbers &d)
{
in>>d.x;
return in;
}
int main()
{
Numbers N;

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

Operator Overloading Implementation:


i. Addition (+): Add two Money objects.
ii. Comparison (==, <, >): Compare two Money objects.
iii. << , >>: To read and display Money Object

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 [ ]

Signature of Teacher / Instructor Date of Completion __ / __ / ______

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
{
--------- ---------- };

• Here class ABC is base class.


• Here class XYZ is derived class.

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.

3.3 Virtual Base Classes

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

• It is not used to create objects.


• As long as no base class constructor takes any arguments, the derived class need not
have a constructor function.

3.5 Constructors in derived classes

General form of defining a derived constructor derived-constructor(arglist1, arglist2,…….arglistN,


arglistD)

Execution of base class constructor

Method Of Inheritance Order Of Execution


class B: public A A (): base constructor
{ }; B (): derived constructor
class A: public B, public C B (); base(first)
{ }; C (): base(second)
A (): derived
class A: public B, virtual public C C (): virtual base
{ }; B (): ordinary base
A (): derived

3.6 Destructors in derived 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.

3.7 Virtual Function

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

3.6 Pure Virtual Function

A pure virtual function is a virtual function that has no definition within the base class.

virtual type func_name(parameter-list) = 0;

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.)

2. Design a multilevel inheritance structure in C++ to represent a simple organizational hierarchy.


Implement a base class Employee, a derived class Manager, and a further derived class
SeniorManager. Each class should have its own specific attributes and methods.

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.

Case Study 2: Employee and Payroll System

Question: Implement an employee payroll system using C++ with inheritance. Create a base class
Employee and derived classes FullTimeEmployee and PartTime

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2.Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor Date of Completion ____/____/___

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.

The try and catch keywords come in pairs:


Example:
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Multiple catch statements:
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {

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.

SET C: Case Studies for Exception Handling

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

4.2.1 Function Template:


It is used to define generic functions. A single function template can work with different
data types at once. It works on different types of data.

Syntax of function template with single parameter:


A function template starts with the keyword template followed by template parameter(s) inside
<> which is followed by function declaration.
template <class T>
returntype functionName(arguments of type T)
{
// Body of function with type T
}
T is a generic name for a data type used by the function. This name can be used within
thefunction definition.

Syntax of function template with Multiple Parameters:


template <class T1,class T2>
returntype functionName(arguments of types T1,T2, ............ )
{
// Body of function
}

Example: Program to illustrate use of Function Template with multiple parameters.


#include<iostream.h>template<class T>
T add(T num1, T num2)

54
{
return (num1 + num2);
}

int main()
{
int result1;
double result2;
// calling with int parameters result1 = add(2, 3);
cout << "2 + 3 = " << result1 << endl;

// calling with double parametersresult2 = add(2.2, 3.3);


cout << "2.2 + 3.3 = " << result2 << endl;

return 0;
}
Output:
2+3=5
2.2 + 3.3 = 5.5

4.2.2 Class Template:


Class templates are used for writing generic class operations. We would need to create a
different class for each data type or create different member variables and functions within a
single class using a class template.

Syntax of class template with single parameter:


template <class T>class className
{
public:
... .. ...
//class member specification with anonymous type T
... .....

... .....

};

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.

Syntax of class template with multiple parameters:


template <class T1, class T2,…..>class className
{
public:
-----
-----
------

};

Example: Program to illustrate use of Class Template with multiple parameters.


#include<iostream.h>
template<classT1,classT2>
Class A
{
T1 a;
T2 b;
public:
A(T1 x,T2y)
{
a = x;b = y;
}
void display()
{
cout<<"Values of a and b are :"<< a<<","<<b<<endl;
}
};
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;

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

0: Not Done [ ] 1: Incomplete [ ] 2.Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor Date of Completion ____/____/___

57

You might also like