0% found this document useful (0 votes)
1 views8 pages

Exception Polymorphism Lab

The OOP Lab Manual covers three main topics: Exception Handling, Polymorphism, and Copy Constructors in C++. It provides learning outcomes, theoretical explanations, practical examples, and lab activities for each topic to enhance understanding and application of these concepts in C++. Additionally, it includes practice questions and a general lab rubric for assessment.

Uploaded by

rameenahmad69
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)
1 views8 pages

Exception Polymorphism Lab

The OOP Lab Manual covers three main topics: Exception Handling, Polymorphism, and Copy Constructors in C++. It provides learning outcomes, theoretical explanations, practical examples, and lab activities for each topic to enhance understanding and application of these concepts in C++. Additionally, it includes practice questions and a general lab rubric for assessment.

Uploaded by

rameenahmad69
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/ 8

OOP Lab Manual: Exception Handling, Polymorphism, and Copy Constructor

Lab #1: Introduction to Exception Handling

Learning Outcomes:

• Understand the concept and importance of exception handling in C++.


• Implement try , catch , and throw blocks to manage runtime errors.
• Apply exception handling in real-world scenarios like banking and input validation.

Theory: What is Exception Handling?

Exception handling is a mechanism in C++ that allows a program to deal with unexpected situations or
runtime errors. Instead of crashing, the program can catch and manage exceptions in a controlled
manner. It enhances code reliability and maintainability.

Need for Exception Handling

In traditional C++ programs, errors like division by zero, invalid memory access, or file I/O issues can
lead to abnormal termination. Exception handling allows separating error-handling code from regular
code using keywords like try , catch , and throw .

Basic Example:

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

try {
if (b == 0) throw "Division by zero not allowed!";
cout << "Result: " << a / b << endl;
} catch (const char* e) {
cout << "Error: " << e << endl;
}
return 0;
}

Sample Output:

Enter two numbers: 10 0


Error: Division by zero not allowed!

1
Scenario-Based Example:

Create a banking system that throws an exception if the withdrawal amount exceeds balance.

class BankAccount {
private:
int balance;
public:
BankAccount(int b) : balance(b) {}
void withdraw(int amount) {
if (amount > balance)
throw "Insufficient balance!";
balance -= amount;
cout << "Withdrawal successful. Remaining: " << balance << endl;
}
};

int main() {
BankAccount acc(1000);
try {
acc.withdraw(1500);
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
}
return 0;
}

Sample Output:

Exception: Insufficient balance!

Practice Questions:

1. Create a program that throws an exception when accessing an out-of-bound array index.
2. Create a class Student that throws an exception if the entered GPA is greater than 4.0 or less
than 0.

Lab Activities:

• Implement a calculator that handles division and throws exceptions for invalid inputs.
• Build a student registration system that validates marks and throws custom exceptions.

Lab #2: Polymorphism & Virtual Functions

Learning Outcomes:

• Understand the concept of polymorphism and its types.


• Use virtual functions for achieving runtime polymorphism.

2
• Apply base class pointers to handle derived class objects dynamically.

Theory: What is Polymorphism?

Polymorphism is the ability of a function or an object to behave differently in different contexts. In C++,
polymorphism is mainly achieved using inheritance and virtual functions. It allows the same interface to
be used for different types of objects.

Types of Polymorphism in C++:

• Compile-time polymorphism: Function and operator overloading.


• Runtime polymorphism: Achieved using virtual functions.

Declaring Pointers to Objects and Base Class References

A base class pointer can be used to refer to derived class objects. This allows for dynamic dispatch of
functions using virtual methods.

Dangling Objects and Dynamic Memory

When using dynamic memory ( new , delete ), it's crucial to manage memory correctly to avoid
memory leaks or dangling pointers (accessing memory after it's deleted).

Basic Virtual Function Example:

class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound\n";
}
};

class Dog : public Animal {


public:
void sound() override {
cout << "Dog barks\n";
}
};

int main() {
Animal* a;
Dog d;
a = &d;
a->sound();
return 0;
}

Sample Output:

3
Dog barks

Inheritance Hierarchy with Pointers Example:

class Shape {
public:
virtual void draw() {
cout << "Drawing shape\n";
}
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing circle\n";
}
};

int main() {
Shape* ptr = new Circle();
ptr->draw();
delete ptr;
return 0;
}

Sample Output:

Drawing circle

Scenario-Based Example:

Design a multimedia player with base class Media and derived classes Audio , Video
implementing play() .

class Media {
public:
virtual void play() {
cout << "Playing media\n";
}
};

class Audio : public Media {


public:
void play() override {
cout << "Playing audio\n";
}
};

4
class Video : public Media {
public:
void play() override {
cout << "Playing video\n";
}
};

int main() {
Media* m[2];
m[0] = new Audio();
m[1] = new Video();

for (int i = 0; i < 2; i++) {


m[i]->play();
delete m[i];
}
return 0;
}

Sample Output:

Playing audio
Playing video

Practice Questions:

1. Create a base class Vehicle with virtual function move() . Create derived classes Car ,
Bike that override it.
2. Create a base class Employee , derived classes Manager , Engineer with overridden
calculateSalary() .

Lab Activities:

• Create an animal zoo simulation using a base class pointer array and derived animal types.
• Implement a simple drawing tool with shapes that use overridden draw() methods.

Lab #3: Copy Constructor and Constant Reference Parameters

Learning Outcomes:

• Understand and apply copy constructors to create duplicate objects.


• Use constant references to improve performance and enforce read-only access.
• Demonstrate copy constructor behavior through class-based examples.

Theory: What is a Copy Constructor?

A copy constructor is a special constructor in C++ used to create a new object as a copy of an existing
object. It is invoked when passing objects by value, returning objects, or explicitly copying.

5
Syntax:

ClassName (const ClassName &obj);

Why Use Constant References?

Using constant reference parameters avoids unnecessary copying and ensures that the passed
argument cannot be modified.

Copy Constructor Example:

class Book {
private:
string title;
public:
Book(string t) : title(t) {}
Book(const Book& b) {
title = b.title;
cout << "Copy constructor called\n";
}
void display() {
cout << "Book Title: " << title << endl;
}
};

int main() {
Book b1("OOP Concepts");
Book b2 = b1;
b2.display();
return 0;
}

Sample Output:

Copy constructor called


Book Title: OOP Concepts

Constant Reference Parameters Example:

void showMessage(const string& msg) {


cout << "Message: " << msg << endl;
}

int main() {
string str = "Welcome to OOP Lab!";
showMessage(str);

6
return 0;
}

Sample Output:

Message: Welcome to OOP Lab!

Scenario-Based Example:

Create a Student class with name and marks. Use copy constructor to copy data to a new student.

class Student {
private:
string name;
int marks;
public:
Student(string n, int m) : name(n), marks(m) {}
Student(const Student& s) {
name = s.name;
marks = s.marks;
cout << "Copy constructor called\n";
}
void display() {
cout << "Name: " << name << ", Marks: " << marks << endl;
}
};

int main() {
Student s1("Ali", 85);
Student s2 = s1;
s2.display();
return 0;
}

Sample Output:

Copy constructor called


Name: Ali, Marks: 85

Practice Questions:

1. Create a class Car with model and price. Demonstrate copy constructor.
2. Write a function to display product details using constant reference parameter.

Lab Activities:

• Design a product inventory system using copy constructors.

7
• Implement a Person class with address and show object copying through copy constructor.

General Lab Rubric

\begin{tabular}{|l|c|}
\hline
\textbf{Assessment Criteria} & \textbf{Marks} \\
\hline
Correct use of OOP concepts (exception handling, polymorphism, copy
constructor) & 10 \\
\hline
Code correctness and functionality & 5 \\
\hline
Code readability and documentation & 3 \\
\hline
Proper output and program testing & 2 \\
\hline
\textbf{Total} & \textbf{20} \\
\hline
\end{tabular}

You might also like