OOP_LabManual_Fall24_IBIT
OOP_LabManual_Fall24_IBIT
LAB MANUAL
IBIT – University of the Punjab OOP – LAB
List of Experiments:
9 Virtual Functions 3
10 Abstract classes 3
11 Interfaces 3
14 Exception Handling 4
Working with Dev C++: Edit, Compile and Run a C++ Program.
1.1 Objective:
1. Learn basic components of a C++ program.
2. Learn compilation process.
3. Learn how to use Dev C++.
4. Learn how to write, edit & run C++ Program.
1.2 Scope:
The student should know the following at the end of this lab:
1. Problem solving
2. How to install run and compile.
3. Basis structure of program
4. Writing Complete Programs
C++ program:
Functions
A function is a block of statements that make a specific kind of processing. Every C++ program
has a main() function. The execution starts from main().
Variables / identifiers
These are used to store data in a program. You must declare a variable before you use it.
IBIT – University of the Punjab OOP – LAB
{ {
} }
IBIT – University of the Punjab OOP – LAB
7. Dev C++ first time configuration box will appear, click next and then ok.
11. Click Compile & Run from the menu item or the displayed icon.
12. If you did not have a syntax error on your code, you will get this output.
IBIT – University of the Punjab OOP – LAB
/* Volume of a sphere */
#include <iostream
> #include<cmath>
#define PI 3.14159
int main()
{
double radius, volume;
cout<<"enter the radius > ";
cin>>radius;
volume = 4.0 / 3.0 * PI * pow(radius,3);
cout<<"the radius of the sphere is :"<<
radius; cout<<"the volume of the sphere is
:"<< volume;
return 0;
}
1.5 Home Work
Launch Dev C++ in your computer and run the above programs
IBIT – University of the Punjab OOP – LAB
Criteria Description
Code
Implementation
Demonstrates a clear understanding of encapsulation, inheritance, and
polymorphism. Implements appropriate access specifiers and utilizes
1. Understanding of inheritance and polymorphism effectively. Utilizes OOP concepts to structure
OOP Principles the code logically.
Code is well-structured, organized, and easy to read. Includes
comments/documentation to explain complex sections, algorithms, and
2. Code Readability design decisions. Follows consistent naming conventions for variables,
and Documentation functions, and classes.
Demonstrates effective memory management practices, including dynamic
memory allocation and deallocation. Avoids memory leaks and dangling
3. Memory pointers by appropriately deallocating memory. Utilizes smart pointers or
Management other memory management techniques where applicable.
Implements robust error handling and exception mechanisms. Handles
exceptions gracefully without causing program termination or undefined
4. Exception behavior. Utilizes try-catch blocks where appropriate and provides
Handling informative error messages.
Utilizes standard library containers and algorithms effectively. Demonstrates
proficiency in utilizing standard library features for common tasks (e.g., file
5. Use of Standard I/O, string manipulation). Chooses appropriate data structures and
Library algorithms for specific tasks.
Problem-Solving
Skills
Designs efficient algorithms to solve given problems. Implements algorithms
using appropriate data structures and control flow constructs. Optimizes
6. Algorithm Design algorithms for performance and resource usage where necessary.
Demonstrates proficiency in debugging techniques. Effectively identifies and
7. Debugging and resolves logical errors, runtime errors, and segmentation faults. Utilizes
Troubleshooting debugging tools and techniques available in the development environment.
Designs comprehensive test cases to validate the functionality of the code.
8. Testing and Executes test cases systematically and identifies edge cases. Verifies the
Validation correctness of the implementation through rigorous testing.
Collaboration and
Communication
Collaborates effectively with team members in group projects. Contributes
9. Collaborative constructively to group discussions and problem-solving sessions. Shares
Skills knowledge and helps peers in understanding complex concepts.
Prepares clear and concise documentation for the codebase. Presents
10. Documentation findings, solutions, and project progress effectively in oral and written
and Presentation formats. Demonstrates professionalism and clarity in communication.
Criteria Description
Technical
Proficiency
1. Proficiency with
Tools and Demonstrates advanced proficiency in using laboratory tools and equipment
Equipment relevant to the subject matter.
2. Execution of Executes laboratory procedures with precision, accuracy, and minimal
Procedures supervision.
3. Troubleshooting Demonstrates adept troubleshooting skills to address unexpected issues or
Skills deviations during experiments.
IBIT – University of the Punjab OOP – LAB
Criteria Description
Experimental
Techniques
4. Experimental Designs experiments effectively, considering variables, controls, and
Design appropriate methods to achieve desired outcomes.
5. Data Collection Collects data meticulously, applies relevant statistical methods for analysis,
and Analysis and interprets results accurately.
Adheres strictly to laboratory safety protocols, ensuring a safe working
6. Laboratory Safety environment for oneself and others.
Critical Thinking and
Problem-Solving
7. Problem Identifies and articulates problems encountered during experiments,
Identification proposing potential solutions or troubleshooting strategies.
8. Adaptability and Demonstrates adaptability in response to changing experimental conditions
Flexibility or unforeseen challenges, adjusting procedures accordingly.
Communication and
Collaboration
9. Communication Communicates experimental procedures, observations, and results
Skills effectively, both verbally and in written reports.
Collaborates seamlessly with peers, sharing responsibilities, insights, and
10. Collaboration resources to accomplish common laboratory objectives.
Professionalism and
Ethics
Upholds ethical standards in research, ensuring honesty, integrity, and
11. Ethical Conduct respect for intellectual property and confidentiality.
12. Time Manages time efficiently to complete experiments within allocated
Management timeframes, meeting deadlines without compromising quality.
IBIT – University of the Punjab OOP – LAB
A program is a collection of small tasks that may depend on other tasks. You can use two
approaches to write a program in programming Fundamental but here you can you use class concept.
Class
In programming, a class is a blueprint for creating objects. It's a fundamental concept in object-
oriented programming (OOP) languages like C++, Java, Python, and many others. A class defines
the properties (attributes or data members) and behaviors (methods or member functions) that
objects of that class will have.
Object
In programming, an object is an instance of a class. It's a fundamental concept in object-oriented
programming (OOP) languages like C++, Java, Python, and many others. When you create an object
from a class, you're essentially creating a specific, unique copy of that class with its own set of data
values.
Objective(s):
The objective of classes is to specify the form of an object and it combines data
representation and methods for manipulating that data into one neat package. The data
and methods within a class are called members of the class.
Tool(s) used:
Dev C++
Visual Studio
How to define:
Class Name{
//Some data
//Some Function
};
Program
For finding max number
#include <iostream>
using namespace std;
class MaximumFinder {
public:
MaximumFinder(int num1, int num2) {
IBIT – University of the Punjab OOP – LAB
this->num1 = num1;
this->num2 = num2;
}
int findMax() {
return (num1 > num2) ? num1 : num2;
}
private:
int num1;
int num2;
};
int main () {
int a = 100;
int b = 200;
int ret;
ret = finder.findMax();
cout << "Max value is : " << ret << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Program 2
#include <iostream>
class Calculator {
public:
return a + b;
IBIT – University of the Punjab OOP – LAB
};
int main () {
Calculator calc;
int a = 100;
int b = 200;
int result;
result = calc.sum(a);
return 0;
When the above code is compiled and executed, it produces the following result −
Program :
#include <iostream>
class NaturalNumbersPrinter {
public:
cout << "Natural numbers between " << start << " and " << end << ": ";
start++;
};
int main() {
NaturalNumbersPrinter printer;
printer.printNaturalNumbers(lowerRange, upperRange);
return 0;
}Output -
5, 6, 7, 8, 9, 10,
#include <iostream>
class NaturalNumbersPrinter {
public:
cout << "Natural numbers between " << start << " and " << end << ": ";
start++;
};
int main() {
NaturalNumbersPrinter printer;
printer.printNaturalNumbers(lowerRange, upperRange);
return 0;
Output -
41
491
14771
25667
28703
Program: Write a C++ program to input a number and check the input is
even or odd. Define a function that accepts the number and return a
value 0 or 1. Return 0 if argument is even, otherwise return 1.
#include <iostream>
class NumberChecker {
IBIT – University of the Punjab OOP – LAB
public:
if (num % 2 == 0)
return 0; // Even
else
return 1; // Odd
};
int main() {
NumberChecker checker;
int num;
if (result == 0)
else
return 0;
Output -
Enter a number: 5
#include <iostream>
class CubeCalculator {
public:
};
int main() {
CubeCalculator calculator;
int num;
cout << "Cube of " << num << " is: " << cube << endl;
return 0;
Output
2^4 = 16
Program :
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
IBIT – University of the Punjab OOP – LAB
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
Program
#include <iostream>using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area () {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
IBIT – University of the Punjab OOP – LAB
Program :
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
IBIT – University of the Punjab OOP – LAB
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Constructor
Objective(s):
The objective of constructor is that it antialise the object automatically when it is created.
Compiler identifies a given member function is a constructor by its name and the return type.Constructor has
the same name as that of the class and it does not have any return type. Also, the constructor is always
public.
Tool(s) used:
Dev C++
Visual Studio
How to define:
class temporary
private:
int x;
float y;
public:
// Constructor
// Body of constructor
... .. ...
};
int main()
Temporary t1;
... .. ...
Program :
IBIT – University of the Punjab OOP – LAB
#include <iostream>
class Rectangle {
public:
Rectangle (int,int);
};
width = a;
height = b;
int main () {
return 0;
Rect area:12
Rectb area:25
Program :
#include <iostream>
class Circle {
double radius;
public:
Circle(double r) { radius = r; }
};
int main () {
return 0;
Foos circumference:62.8319
A class constructor is a special member function of a class that is executed whenever we create new objects
of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.
Task 4:
#include <iostream>
class Line {
public:
private:
double length;
};
Line::Line(void) {
IBIT – University of the Punjab OOP – LAB
length = len;
return length;
int main() {
Line line;
line.setLength(6.0);
return 0;
When the above code is compiled and executed, it produces the following result −
Length of line : 6
IBIT – University of the Punjab OOP – LAB
Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can have parameters. This
helps you to assign initial value to an object at the time of its creation as shown in the following example −
Program :
#include <iostream>
class Line {
public:
private:
double length;
};
cout << "Object is being created, length = " << len << endl;
length = len;
length = len;
return length;
int main() {
Line line(10.0);
IBIT – University of the Punjab OOP – LAB
line.setLength(6.0);
return 0;
When the above code is compiled and executed, it produces the following result −
Length of line : 10
Length of line : 6
IBIT – University of the Punjab OOP – LAB
A destructor is a special member function of a class that is executed whenever an object of it's class goes out
of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value
nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of
the program like closing files, releasing memories etc.
Tool(s) used:
Dev C++
Visual Studio
Program :
#include <iostream>
class Line {
public:
private:
double length;
};
Line::Line(void) {
Line::~Line(void) {
IBIT – University of the Punjab OOP – LAB
length = len;
return length;
int main() {
Line line;
line.setLength(6.0);
return 0;
When the above code is compiled and executed, it produces the following result −
Length of line : 6
Copy Constructor
Program
#include<iostream>
#include<cstring>
class test{
int code;
float price;
public:
IBIT – University of the Punjab OOP – LAB
void disp();
};
code=c;
price=p;
code=t.code;
price=t.price;
void test::disp(){
cout<<code<<endl<<price;
int main(){
test t1(5,6.6);
test t2(t1);
test t3=t2;
t1.disp();
t2.disp();
t3.disp();
return 0;
}
IBIT – University of the Punjab OOP – LAB
Constructor Overloading
Objective(s):
The objectives of constructor overloading is that we can use the constructor of same name with different
parameter.
Tools:
Dev C++
Visual Studio
Program:
#include <iostream>
class student{
int id ;
float marks;
public:
student(){
cout<<"hello"<<endl;
student(int a){
id=a;
cout<<a<<endl;
id=a;
marks =b;
}
IBIT – University of the Punjab OOP – LAB
~student(){
cout<<"object is deleted"<<endl;
void display(){
cout<<id<<endl<<marks;
}*/
};
int main(){
student s,s1(5);
/*s1.display();
s2.display();
s.display();
return 0;
Program :
#include <iostream>
class Line {
public:
private:
double length;
};
Line::Line(void) {
Line::~Line(void) {
length = len;
return length;
int main() {
Line line;
line.setLength(6.0);
return 0;
Program :
#include<iostream>
#include<cstring>
class rectangle{
int length;
int height;
int width;
char name[10];
public:
rectangle()
length=10;
IBIT – University of the Punjab OOP – LAB
width=20;
height=30;
cout<<length<<endl<<height<<endl<<width<<endl<<endl;
rectangle(int len){
length=len;
length=len;
width=wid;
length=len;
height=h;
h=30;
cout<<"mutiply"<<len*wid*h;
name=name;
cin>>name;
cout<<name;
};
int main(){
//string a;
char a;
rectangle r,r1(5),r2(5,6),r3(1,2,3),r4(a);
int main() {
int n;
cout << "Enter the number of data values: ";
cin >> n;
int* data = new int[n];
cout << "Enter the data values: ";
for (int i = 0; i < n; ++i) {
cin >> data[i];
}
IBIT – University of the Punjab OOP – LAB
delete[] data;
}
// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}
// Non-const member function to print the elements of the array
void printElements() {
cout << "Elements of the array (non-const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
// Const member function to print the elements of the array
void printElements() const {
cout << "Elements of the array (const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;
// Accepting values from the user and storing them in the array
IBIT – University of the Punjab OOP – LAB
arrayPrinter.acceptValues();
// Printing elements of the array using the non-const member function
arrayPrinter.printElements();
// Printing elements of the array using the const member function
const ArrayPrinter constArrayPrinter = arrayPrinter;
constArrayPrinter.printElements();
return 0;
}
return arr;
}
// Const member function to sort the array in ascending order
const int* sortArray(const int* arr, int size) {
// Creating a copy of the array to avoid modifying the original array
int* sortedArray = new int[size];
for (int i = 0; i < size; ++i) {
sortedArray[i] = arr[i];
}
// Sorting the copied array
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (sortedArray[j] > sortedArray[j + 1]) {
// Swap elements if they are in the wrong order
int temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
};
int main() {
const int size = 10;
int arr[size] = {5, 2, 9, 1, 7, 3, 6, 8, 4, 10};
// Creating an object of ArraySorter class
ArraySorter arraySorter;
// Sorting the array using the non-const member function
int* sortedArray1 = arraySorter.sortArray(arr, size);
IBIT – University of the Punjab OOP – LAB
class ArraySorter {
public:
// Non-const member function to sort the array in descending order
int* sortArrayDescending(int* arr, int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
IBIT – University of the Punjab OOP – LAB
return sortedArray;
}
};
int main() {
const int size = 10;
int arr[size] = {5, 2, 9, 1, 7, 3, 6, 8, 4, 10};
// Sorting the array in descending order using the non-const member function
int* sortedArray1 = arraySorter.sortArrayDescending(arr, size);
// Sorting the array in descending order using the const member function
const int* sortedArray2 = arraySorter.sortArrayDescending(arr, size);
class ArrayPrinter {
private:
int* data;
const int size;
public:
// Constructor
ArrayPrinter() : size(5) {
data = new int[size];
}
// Destructor
~ArrayPrinter() {
delete[] data;
}
IBIT – University of the Punjab OOP – LAB
// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}
int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;
IBIT – University of the Punjab OOP – LAB
// Accepting values from the user and storing them in the array
arrayPrinter.acceptValues();
return 0;
}
// Destructor
~ArrayPrinter() {
IBIT – University of the Punjab OOP – LAB
delete[] data;
}
// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}
// Non-const member function to print the elements of the array in reverse order
void printReverse() {
cout << "Elements of the array in reverse order (non-const function): ";
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}
// Const member function to print the elements of the array in reverse order
void printReverse() const {
cout << "Elements of the array in reverse order (const function): ";
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}
};
IBIT – University of the Punjab OOP – LAB
int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;
// Accepting values from the user and storing them in the array
arrayPrinter.acceptValues();
// Printing elements of the array in reverse order using the non-const member function
arrayPrinter.printReverse();
// Printing elements of the array in reverse order using the const member function
const ArrayPrinter constArrayPrinter = arrayPrinter;
constArrayPrinter.printReverse();
return 0;
}
IBIT – University of the Punjab OOP – LAB
Tool(s) used:
Dev C++
Visual Studio
………………………………………………………………………………………………
Program :
#include <iostream>
#include <cstring>
using namespace std;
class Book {
private:
static int nextId;
char title[50];
char author[50];
char subject[100];
int book_id;
public:
// Constructor
Book(const char* t, const char* a, const char* s) {
strcpy(title, t);
strcpy(author, a);
strcpy(subject, s);
book_id = nextId++;
IBIT – University of the Punjab OOP – LAB
int main() {
// Creating Book objects
Book book1("Learn C++ Programming", "Chand Miyan", "C++ Programming");
Book book2("Telecom Billing", "Yakit Singha", "Telecom");
return 0;
}
……………………………………………………………………………………………………
Program :
#include <iostream>
#include <cstring>
using namespace std;
class Book {
private:
static int nextId;
char title[50];
char author[50];
char subject[100];
int book_id;
public:
// Constructor
Book(const char* t, const char* a, const char* s) {
strcpy(title, t);
strcpy(author, a);
strcpy(subject, s);
book_id = nextId++;
IBIT – University of the Punjab OOP – LAB
int main() {
// Creating Book objects
Book book1("Learn C++ Programming", "Chand Miyan", "C++ Programming");
Book book2("Telecom Billing", "Yakit Singha", "Telecom");
return 0;
}
……………………………………………………………………………………………………
IBIT – University of the Punjab OOP – LAB
Program
#include <iostream>
#include <cstring>
using namespace std;
// Structure definition
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
// Declare Book1 and Book2 of type Books
struct Books Book1, Book2;
// Book 1 specification
strcpy(Book1.title, "Learn C++ Programming");
strcpy(Book1.author, "Chand Miyan");
strcpy(Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
IBIT – University of the Punjab OOP – LAB
// Book 2 specification
strcpy(Book2.title, "Telecom Billing");
strcpy(Book2.author, "Yakit Singha");
strcpy(Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
}
………………………………………………………………………………………………
When the above code is compiled and executed, it produces the following result −
……………………………………………………………………………………………………
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
……………………………………………………………………………………………………
Program :
#include<iostream>
#include<cstring>
using namespace std;
string designation;
Address address1;
public:
// Function to set employee details
void setDetails(int id, const char* n, const char* desig, int houseNo, const char* c, const
string& cntry) {
emp_id = id;
strcpy(name, n);
designation = desig;
address1.house_no = houseNo;
strcpy(address1.city, c);
address1.country = cntry;
}
}
};
int main() {
// Creating an object of Employee
Employee emp;
emp.setDetails(2, "Ali", "Head", 5, "Lahore", "Pakistan");
// Printing employee details using the overloaded function with a different signature in the
base class
emp.printDetails(101);
cout << endl;
Manager manager;
manager.setDetails(3, "John", "Manager", 10, "London", "UK");
return 0;
}
Program
Function Overloading:
Area Calculated
#include <iostream>
using namespace std;
// Function to calculate the area of a square
int calculateArea(int side) {
return side * side;
}
// Overloaded function to calculate the area of a rectangle
int calculateArea(int length, int breadth) {
return length * breadth;
}
int main() {
cout << "Area of square: " << calculateArea(5) << endl;
cout << "Area of rectangle: " << calculateArea(4, 6) << endl;
return 0;
}
Sum of Numbers:
#include <iostream>
using namespace std;
IBIT – University of the Punjab OOP – LAB
int main() {
cout << "Sum of two numbers: " << sum(5, 3) << endl;
cout << "Sum of three numbers: " << sum(4, 6, 2) << endl;
return 0;
}
Operator Overloading
Unary minus (-) operator overloading program in C++
/*C++ program for unary minus (-) operator overloading.*/
#include<iostream>
using namespace std;
class NUM
{
private:
int n;
public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
IBIT – University of the Punjab OOP – LAB
void dispNum(void)
{
cout << "value of n is: " << n;
}
//unary - operator overloading
void operator - (void)
{
n=-n;
}
};
int main()
{
NUM num;
num.getNum(10);
-num;
num.dispNum();
cout << endl;
return 0;
}
Unary increment (++) and decrement (--) operator overloading program in
C++
// C++ program for unary increment (++) and decrement (--) operator
overloading
#include <iostream>
using namespace std;
class NUM {
private:
int n;
public:
// function to get number
IBIT – University of the Punjab OOP – LAB
void getNum(int x)
{
n = x;
}
// function to display number
void dispNum(void)
{
cout << "value of n is: " << n;
}
// unary ++ operator overloading
void operator++(void)
{
n = ++n;
}
// unary -- operator overloading
void operator--(void)
{
n = --n;
}
};
int main()
{
NUM num;
num.getNum(10);
++num;
cout << "After increment - ";
num.dispNum();
cout << endl;
--num;
cout << "After decrement - ";
IBIT – University of the Punjab OOP – LAB
num.dispNum();
cout << endl;
return 0;
}
Function Overloading
Objective(s):
Objectives of function is to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator overloading
respectively.
Tool(s) used:
Dev C++
Visual Studio
An overloaded declaration is a declaration that is declared with the same name as a
previously declared declaration in the same scope, except that both declarations have
different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call the
function or operator with the parameter types specified in the definitions. The process of
selecting the most appropriate overloaded function or operator is called overload
resolution.
Function Overloading in C++
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ only
by return type.
Program :
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
IBIT – University of the Punjab OOP – LAB
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
return 0;
}
Program :
//function with same name and different parameters or arguments
#include<iostream>
using namespace std;
class book{
public:
IBIT – University of the Punjab OOP – LAB
void print(){
// id=a;
cout<<"Books Record "<<endl;
// id=a;
cout<<"Book id is ="<<a<<endl;
}
void print(string t){
//title=t;
//code=c;
cout<<"Book title is ="<<c<<endl;
}
void print(int a,string s,char c){
//id=a;
// title=s;
//code=c;
cout<<"Book id is ="<<a<<endl;
IBIT – University of the Punjab OOP – LAB
int main(){
book b;
b.print();
b.print(5);
b.print("Ali");
b.print('t');
b.print(5,"abc",'a');
return 0;
}
IBIT – University of the Punjab OOP – LAB
Introduction to Inheritance
Objective(s):
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of
an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
Tool(s) used:
Dev C++
Visual Studio
Consider a base class Shape and its derived class Rectangle as follows –
Program :
IBIT – University of the Punjab OOP – LAB
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
void setHeight(int h) {
height = h;
protected:
int width;
int height;
};
// Derived class
public:
int getArea() {
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Total area: 35
-----------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB
We can summarize the different access types according to - who can access them in the
following way −
Type of Inheritance
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-
specifier as explained above.
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended
syntax −
Where access is one of public, protected, or private and would be given for every base
class and they will be separated by comma as shown above. Let us try the following
example –
Program :
#include <iostream>
class Shape {
public:
void setWidth(int w) {
width = w;
void setHeight(int h) {
height = h;
protected:
int width;
int height;
IBIT – University of the Punjab OOP – LAB
};
class PaintCost {
public:
};
// Derived class
public:
int getArea() {
};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
IBIT – University of the Punjab OOP – LAB
Rect.setHeight(7);
area = Rect.getArea();
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Total area: 35
-----------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB
Multilevel Inheritance:
Objective(s):
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than
one base class. Theinheritance we learnt earlier had the concept of one base class or
parent. The problem with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
Program :
#include<iostream>
#include<cstring>
//base class
class animal {
protected:
int legs;
string hair;
public:
legs=a;
hair=b;
IBIT – University of the Punjab OOP – LAB
};
//child class
protected :
string color;
public:
color=c;
cout<<c<<endl;
void bodgshape(){
cout<< legs<<endl<<hair;
};
IBIT – University of the Punjab OOP – LAB
public:
void speed(){
cout<<"80 kmph";
};
int main(){
//lion l;
//l.body(4,"hair");
//l.color1("blue");
//l.bodgshape();
lionspeed s;
s.body(4,"Hair");
s.color1("white");
IBIT – University of the Punjab OOP – LAB
s.bodgshape();
s.speed();
Output:
white
Hair80 kmph
IBIT – University of the Punjab OOP – LAB
Association
Objective(s):
Association is a simple structural connection or channel between classes and is a
relationship where all objects have their own lifecycle and there is no owner.
Lets take an example of Department and Student.
Multiple students can associate with a single Department and single student can associate
with multiple Departments, but there is no ownership between the objects and both have
their own lifecycle. Both can create and delete independently.
Program :
#include<iostream.h>
class Student;
class Department
{
char* name_p;
public:
Department(char *dName)
{
cout<<"Department::ctor\n";
name_p = new char(sizeof(strlen(dName)));
name_p = dName;
}
IBIT – University of the Punjab OOP – LAB
~Department()
{
cout<<"Department::dtor\n";
delete(name_p);
}
};
class Student
{
char* name_p;
public:
Student(char *sName)
{
cout<<"Student::ctor\n";
name_p = new char(sizeof(strlen(sName)));
name_p = sName;
}
char* sName()const
{
return(name_p);
}
IBIT – University of the Punjab OOP – LAB
~Student()
{
cout<<"Student::dtor\n";
delete(name_p);
};
};
class Course
{
Student * std_p;
Department * dept_p;
char * courseName_p;
public:
if (index < 4)
{
courseName_p = new char(sizeof(strlen(crseName)));
courseName_p = crseName;
IBIT – University of the Punjab OOP – LAB
~Course()
{
cout<<"Course:dtor\n";
delete (courseName_p);
};
int main()
{
int i;
cout<<"\n";
cout<<"\n";
cout<<"Here class Course Associates Student and Department, with a Course name ...\
n";
Course course1("DataStructure",studentNames[0], departNames[1]);
Course course2("Maths",studentNames[3], departNames[0]);
Course course3("Geometry",studentNames[2], departNames[0]);
IBIT – University of the Punjab OOP – LAB
cout<<"\n";
cout<<"\n";
cout<<"Deletion of objects...\n\n";
cout<<"\n";
cout<<"\n";
return(0);
}
output:
IBIT – University of the Punjab OOP – LAB
------
Here class Course Associates Student and Department, with a Course name ...
Course:ctor
Course:ctor
Course:ctor
Course:ctor
Deletion of objects...
Student::dtor
Student::dtor
Student::dtor
Student::dtor
IBIT – University of the Punjab OOP – LAB
Department::dtor
Department::dtor
Course:dtor
Course:dtor
Course:dtor
Course:dtor
IBIT – University of the Punjab OOP – LAB
Aggregation
Objective(s):
To qualify as an aggregation, a whole object and its parts must have the following
relationship:
• The part (member) is part of the object (class)
• The part (member) can belong to more than one object (class) at a time
• The part (member) does not have its existence managed by the object (class)
• The part (member) does not know about the existence of the object (class)
• pointer variables
• Use reference that point the object that lives outside teh scope
• Pointer object /deep copy
• Not responsible for creation/destruction
Like a composition, an aggregation is still a part-whole relationship, where the parts are
contained within the whole, and it is a unidirectional relationship. However, unlike a
composition, parts can belong to more than one object at a time, and the whole object is
not responsible for the existence and lifespan of the parts. When an aggregation is created,
the aggregation is not responsible for creating the parts. When an aggregation is
destroyed, the aggregation is not responsible for destroying the parts.
Program :
class alpha
{
int x;
public:
void read-x()
{
cin>>x;
}
void print.x()
{
IBIT – University of the Punjab OOP – LAB
cout<<x;
}
};
class beta
{
int y;
alpha *a;
public:
beta(alpha*p)
}
a=p;
}
void main()
{
alpha a1;
beta b1(&a1);
}
Task 2:
#include<iostream>
using namespace std;
class processor{
private:
double clockspeed;
public:
processor(){
clockspeed=2.6;
}
processor(double cspeed){
clockspeed=cspeed;
IBIT – University of the Punjab OOP – LAB
double getclockspeed(){
return clockspeed;
}
void setclockspeed(double cs){
clockspeed=cs;
}
};
class computer{
processor *processor1;
public:
void set processor (processor *processor1){
this->processor1->setclockspeed(processor1->getclockspeed());
this->processor1->setclockspeed(11111);
}
void print(){
//cout<<"Operating System"<<operatingsystem;
cout<<"Clock speed "<<processor1->getclockspeed();
}
IBIT – University of the Punjab OOP – LAB
};
int main(){
processor p(5.5);
//calling parameterize contructor
{
computer c1;
c1.setprocessor(&p);
)
c1.print();
}
cout<<" Clock Speed "<<p.getclockspeed();
return 0;
}
IBIT – University of the Punjab OOP – LAB
Composition
Composition is again specialize form of Aggregation. It is a strong type of Aggregation.
Here the Parent and Child objects have coincident lifetimes. Child object dose not have it's
own lifecycle and if parent object gets deleted, then all of it's child objects will also be
deleted.
Implementation details:
House can contain multiple rooms there is no independent life for room and any room can
not belong to two different house. If we delete the house room will also be automatically
deleted.
Program :
#include<iostream.h>
class House;
class Room
{
public:
IBIT – University of the Punjab OOP – LAB
Room()
{
};
if(NULL != myHse_p)
{
name_p = new char(sizeof(strlen(myName)));
name_p = myName;
}
else
{
cout<<"Oops House itself is not Created Yet ...\n";
}
};
~Room()
{
cout<<"Room:dtor\n";
myHse_p = NULL;
delete (name_p);
IBIT – University of the Punjab OOP – LAB
};
void disp()
{
cout<< name_p;
cout<<"\n";
}
private:
House * myHse_p;
char * name_p;
};
class House
{
public:
House(char *myName)
{
cout<<"House::ctor\n";
name_p = new char(sizeof(strlen(myName)));;
name_p = myName;
Room::initList_v(roomsList_p);
IBIT – University of the Punjab OOP – LAB
Room* myRoom;
Room::createRoom_v(myRoom, this, "Kitchen");
roomsList_p[0] = myRoom;
~House()
{
cout<<"House:dtor\n";
unsigned int i;
}
delete [] roomsList_p;
delete (name_p);
}
void disp()
IBIT – University of the Punjab OOP – LAB
{
cout<<"\n\nName of the House :"<<name_p;
if(roomsList_p != NULL)
{
unsigned int i;
cout<<"\n\nRooms details...\n";
for(i=0; i<3; ++i)
{
if(NULL != roomsList_p[i])
{
roomsList_p[i]->disp();
}
}
cout<<"\n\n";
}
}
private:
char* name_p;
Room* roomsList_p[3];
};
int main()
{
cout<<"\n\nHouse details...\n";
hse.disp();
cout<<"Here House itself creates the Rooms and Deletes as well, before it gets deletd...\
n";
return(0);
}
output:
-------
Example of Composition Relationship
-----------------------------------------
House::ctor
Room::ctor
Room::ctor
Room::ctor
House details...
Name of the House :Vishranti Nilaya
Rooms details...
Kitchen
BedRoom
Drwaing Room
Here House itself creates the Rooms and Deletes as well, before it gets deletd...
House:dtor
Delete all the Rooms ...
IBIT – University of the Punjab OOP – LAB
Room:dtor
Room:dtor
Room:dtor
Program :
#include <iostream>
#include <string>
using namespace std;
class Birthday{
public:
Birthday(int cmonth, int cday, int cyear){
cmonth = month;
cday = day;
cyear = year;
}
void printDate(){
cout<<month <<"/" <<day <<"/" <<year <<endl;
}
private:
int month;
int day;
int year;
};
class People{
public:
IBIT – University of the Punjab OOP – LAB
}
void printInfo(){
cout<<name <<" was born on: ";
dateOfBirth.printDate();
}
private:
string name;
Birthday dateOfBirth;
};
int main() {
Birthday birthObject(7,9,97);
People infoObject("Lenny the Cowboy", birthObject);
infoObject.printInfo();
}-------------------------------------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne −
friend class ClassTwo;
Program :
#include <iostream>
using namespace std;
class Box {
double width;
public:
IBIT – University of the Punjab OOP – LAB
return 0;
}
Width of box : 10
Program :
Addition of members of two different classes using friend Function
#include <iostream>
using namespace std;
// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
IBIT – University of the Punjab OOP – LAB
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Output
Sum: 13
IBIT – University of the Punjab OOP – LAB
Program :
#include<iostream>
using namespace std;
class box{
int a,b,c;
public:
void getdata(int x,int y,int z);
void operator++();
void disp();
};
b=y;
c=z;
}
void box::operator++(){
a=++a;
b=++b;
c=++c;
void box::disp(){
cout<<"first : \t\t"<<a<<endl<<"second : \t\t"<<b<<endl<<"third : \t\t"<<c<<endl;
}
int main(){
box b1,b2;
b1.getdata(-2,3,4);
b1.disp();
++b1;
b1.disp();
}
Program :
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
IBIT – University of the Punjab OOP – LAB
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
D1.displayDistance(); // display D1
return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
Program :
//binary operator overloading
#include<iostream>
using namespace std;
class student{
private:
int num;
int marks;
public:
student(){
num=0;
marks=0;
}
IBIT – University of the Punjab OOP – LAB
}
student operator +(student s){
//first num direct accessing the value but accessing second object
value we (s.num)by accessing second object value
student temp;//creating object for returning object becasue we
have student as a return type
temp.num=num+s.num;
temp.marks=marks+s.marks;
return temp;
}
void display(){
cout<<"number :"<<num<<endl<<"marks :"<<marks<<endl;
}
};
int main(){
student s(2,3),s1(6,7),s2;
//s=student(6,7);//explicitly
//s1=student(6,7);
s2=s+s1;
cout<<"value of 1"<<endl;
s.display();
cout<<"value of 2"<<endl;
s1.display();
cout<<"value of 3"<<endl;
IBIT – University of the Punjab OOP – LAB
s2.display();
return 0;
}
Program :
#include <iostream>
using namespace std;
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
IBIT – University of the Punjab OOP – LAB
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
int id;
string name;
public :
cin>>a>>b;
IBIT – University of the Punjab OOP – LAB
id=a;
name=b;
}
void get(){
cout<<"set of id :"<<id<<endl;
cout<<"set of id :"<<name<<endl;
}
// now here we declare two class which are ostream and
istream,basically we can overload cout,cin by using friend class function
//now we are using two friend function of two classess
//mostly we only declares friend function in class and define outside the
class but here we declare and define friend function in the class
int a;
string b;
Student s;
s.set(a,b);
s.get();
cout<<"Now we are going to display Operator Overloading"<<endl;
cin>>s;
cout<<s;
}
Program :
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
IBIT – University of the Punjab OOP – LAB
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
int main() {
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
}
When the above code is compiled and executed, it produces the
following result −
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
IBIT – University of the Punjab OOP – LAB
_
IBIT – University of the Punjab OOP – LAB
__________________________________________________________________
IT260 - Object Oriented Programming Instructor:
Polymorphism
Objective(s):
Polymorphism is an object oriented programming concept that allows a class to have different
form or behavior for example a trumpet a flute .
Task 1:
include<iostream>
using namespace std;
class A
{
int a;
public:
A()
{
a=0;
}
A(int x)
{
a=x;
}
virtual void display()
//pure virtual function
/*C++ virtual function is a member function of a class, whose functionality can be over-
ridden
in its derived classes. The whole function body can be replaced with a new set of implementation
in the derived class. The concept of c++ virtual functions is different from C++
Function overloading.
void display(){
//A::display();
cout<<"The value of b is"<<b<<endl;
}
};
class C:public A{
int c;
public:
C():A()
{
IBIT – University of the Punjab OOP – LAB
c=0;
}
C(int x, int y):A(x)
{
c=y;
}
void display(){
A::display();
};
int main()
{
B x(10,50);
x.display();
cout<<endl;
C y;
y.display();
A z;
z.display();
}
Program :
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
IBIT – University of the Punjab OOP – LAB
public:
void set_values (int a, int b)
{ width=a;
height=b; }
virtual int area ()
{ return 0; }
};
class Rectangle: public Polygon {
public:
int area ()
{ return width * height; }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 ;//declare the pointer
ppoly1= ▭// store the address
Polygon * ppoly2 ;
ppoly2= &trgl;
Polygon * ppoly3 ;
IBIT – University of the Punjab OOP – LAB
ppoly3 = &poly;
ppoly1->set_values (4,5);//call the value
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
Task 3:
#include<iostream>
using namespace std;
class base{
public:
void disp()
{
cout<<"base class"<<endl;
}
virtual void show()
{
cout<<"Base class show:";
}
};
class derived:public base
{
void disp()
{
cout<<"derived class"<<endl;
IBIT – University of the Punjab OOP – LAB
}
void show()
{
cout<<"derived class show";
}
};
int main()
{
base*ptr;
base objb;
objb.disp();
objb.show();
derived objd;
ptr=&objd;//store address
ptr->disp();//call the function
ptr->show();
return 0;
}
IBIT – University of the Punjab OOP – LAB
Virtual Function
A virtual function is a function in a base class that is declared using the keyword virtual.
Defining in a base class a virtual function, with another version in a derived class, signals
to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called. This sort of operation is
referred to as dynamic linkage, or late binding.
Program :
// CPP program to illustrate
#include<iostream>
class base
public:
void show ()
};
IBIT – University of the Punjab OOP – LAB
public:
void print ()
void show ()
};
int main()
base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
Program 2 :
#include<iostream>
IBIT – University of the Punjab OOP – LAB
class A{
public:
};
class B:public A{
private:
int val1;
public:
B(int x){
val1= x;
void disp(){
};
class C:public A{
private:
int val2;
public:
C(int x){
val2= x;
void disp(){
};
int main(){
A *basep;
B objb(100);
basep=&objb;
basep->disp();
C objc(200);
basep=&objc;
basep->disp();
return 0;
Templates
Objective(s):
Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers
like iterators and algorithms are examples of generic programming and have been developed using
template concept.
There is a single definition of each container, such as vector, but we can define many different
kinds of vectors for example, vector <int> or vector <string>.
Function Templates
Program :
#include<iostream>
using namespace std;
template <class t>
t sum(t a,t b){
return a+b;
}
int main(){
cout<<sum(5,6.5);
}
s=s+a[i];
}
return s;
}
int main(){
int a[5]={1,2,3,4,5};
cout<<sum(a,5);
}
Program :
#include <iostream>
#include <string>
IBIT – University of the Punjab OOP – LAB
int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
}
template <class t>
t sum(t a,t b,t c){
return a+b+c;
}
int main(){
cout<<sum(6,6)<<endl;
cout<<sum(6.6,6.6,6.6);
Class Template
Just as we can define function templates, we can also define class templates. The general
form of a generic class declaration is shown here −
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a comma-separated
list.
Program :
#include<iostream>
using namespace std;
template <class t>
IBIT – University of the Punjab OOP – LAB
class student{
t a, b;
public:
void name(t a1,t b1){
a=a1;
b=b1;
}
void display(){
cout<<a<<" "<<b;
}
t sum();
//if outside the class then we template syntax line again and then call function
//template<class t>
//t classname<t>::functionname()
};
template <class t>
t student<t>::sum()
{
return a+b;
}
int main(){
student <int> s;
s.name(5,6);
s.display();
cout<< s.sum();
}
IBIT – University of the Punjab OOP – LAB
Program :
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
elems.push_back(elem);
}
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
IBIT – University of the Punjab OOP – LAB
#include <iostream>
#include <stdexcept>
if (denominator == 0) {
int main() {
try {
return 0;
Output 1
Enter numerator: 72
Enter denominator: 0
Output 2
Enter numerator: 72
Enter denominator: 3
72 / 3 = 24
The above program divides two numbers and displays the result. But an exception
occurs if the denominator is 0.
To handle the exception, we have put the code divide = numerator /
denominator; inside the try block. Now, when an exception occurs, the rest of the code
inside the try block is skipped.
The catch block catches the thrown exception and executes the statements inside it.
If none of the statements in the try block generates an exception, the catch block is
skipped.
Working of
try, throw, and catch statements in C++
Notice that we have thrown the int literal 0 with the code throw 0;.
We can throw any literal or variable or class, depending on the situation and depending
on what we want to execute inside the catch block.
The catch parameter int num_exception takes the value passed by the throw statement i.e.
the literal 0.
IBIT – University of the Punjab OOP – LAB
Write a program to implement the exception handling with multiple catch statements.
#include<iostream.h> void
test(int x)
{
try
{
if(x==1)
throw x;
else
if(x==0)
throw 'x';
else
if(x==-1)
throw 1.0;
} cout<<"End of try-black\n";
catch(char c)
{
cout<<"Caught a Character\n";
}
catch(int c)
{
cout<<"Caught an Integer\n";
}
catch(double c)
{
cout<<"Caught a Double\n";
}
int main()
{
return 0;
}
IBIT – University of the Punjab OOP – LAB
#include<iostream.h>
if(y==0.0)
throw y;
else
cout<<"Division ="<<x/y<<"\n";
}
catch(double)
{
cout<<"End of Function\n";
}
int main()
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{
#include<iostream.h>
if(x==0)
throw 'x';
else
if(x == 1)
throw x;
else
if(x == -1)
throw 1.0;
cout<<"End of Function Block\n";
}
int main()
{
try
{
}
Lahore Garrison University Department of Software Engineering
catch(char c)
{
cout<<"Caught a Character\n";
}
catch(int m)
{
cout<<"Caught an Integer\n";
}
catch(double d)
{
cout<<"Caught a Double\n";
}
PAGE \* MERGEFORMAT 30