0% found this document useful (0 votes)
18 views

Lab Report 07

Uploaded by

Fabeha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lab Report 07

Uploaded by

Fabeha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Lab No.

4 Operator
Overloading
4.1 Objectives of the lab:
Introducing the concepts of
operator overloading and
overloading different operators
such as
14 Arithmetic operators
15 Relational operators
16 Logical operators
17 Unary operators
Lab No.4 Operator
Overloading
4.1 Objectives of the lab:
Introducing the concepts of
operator overloading and
overloading different operators
such as
14 Arithmetic operators
15 Relational operators
16 Logical operators
17 Unary operators
Lab No.4 Operator
Overloading
4.1 Objectives of the lab:
Introducing the concepts of
operator overloading and
overloading different operators
such as
14 Arithmetic operators
15 Relational operators
16 Logical operators
17 Unary operLa
DEPARTMENT OF COMPUTER & SOFTWARE
ENGINEERING
COLLEGE OF E&ME, NUST, RAWALPINDI

EC-201 Object Oriented Programming


LAB MANUAL – 07

Course Instructor: Anum Abdul Salam


Lab Instructor: Engr. Eman Fatima

Student Name: Fabeha Zahid Mahmood


Degree/ Syndicate:45/B

Trait Obtained Maximum


Marks Marks
R1 Application Functionality and 3
Specification
30%
R2 Readability 1
10%
R3 Reusability 1
10%
R4 Object Oriented Design 3
30%
R5 Efficiency 1
10%
R6 Delivery 1
10%
R7 Plagiarism below 70% 1

Total 10

Total Marks = O𝒃𝒕𝒂𝒊𝒏𝒆𝒅 𝑴𝒂𝒓𝒌𝒔 (∑6𝟏 𝑹𝒊 ∗ 𝑹7)

Tool used: Microsoft Visual Studio


Lab Objective:
The main purpose of this lab is to understand the concept of operator overloading and its
significance in object-oriented programming. Students will learn how to overload different types
of operators (e.g., arithmetic, relational, assignment, and stream operators) to extend the
functionality of user-defined classes. Students will practice the use of operator overloading for
common operations, such as adding two objects and comparing objects etc.

Lab Tasks:
1. Create a C++ class called Time to represent time values, with attributes for hours and
minutes only. Overload the (+) operator within the (Time) class to add two (Time) objects.
This operator should add the hours and minutes separately. In the main function:
 Create two Time objects, (time1) and (time2).
 Input the values of hours and minutes for both (time1) and (time2).
 Use the overloaded (+) operator to add (time1) and (time2) together and create a new
(Time) object called (resultTime).
 Display the values of (resultTime) to show the addition of the times.
UML Diagram:
Source Code:

#include <iostream>
using namespace std;

class Time {
private:
int hours;
int minutes;

public:
// Constructor
Time(int h = 0, int m = 0) {
sethours(h);
setminutes(m);
}

// Setters
void sethours(int h) {
hours = h;
}

void setminutes(int m) {
minutes = m;
}

// Getters
int gethours() const {
return hours;
}

int getminutes() const {


return minutes;
}

// Overloading + operator to add two Time objects


Time operator+(Time const& t) const {
int h = hours + t.hours;
int m = minutes + t.minutes;

// Handle minutes overflow


h += m / 60;
m %= 60;

return Time(h, m);


}
};
// Overloading << operator for output outside the class
ostream& operator<<(ostream& out, const Time& t) {
out << t.gethours() << " hours and " << t.getminutes() << " minutes";
return out;
}

// Overloading >> operator for input outside the class


istream& operator>>(istream& in, Time& t) {
int h, m;
cout << "Enter hours: ";
in >> h;
t.sethours(h);
cout << "Enter minutes: ";
in >> m;
t.setminutes(m);
return in;
}

int main() {
Time time1, time2;

cout << "Enter first time:" << endl;


cin >> time1;

cout << "Enter second time:" << endl;


cin >> time2;

// Adding time1 and time2


Time resultTime = time1 + time2;

// Displaying result
cout << "Resulting time after addition: " << resultTime << endl;

return 0;
}
Output:
2. Create a C++ class called `Int` to represent a custom integer data type. Overload the `+`
operator to add two `Int` objects. If the result exceeds the normal range of integers, print a
warning and terminate the program. Overload the `-` operator to subtract one `Int` object
from another. Handle overflow similarly. Overload the `*` operator to multiply two `Int`
objects. Handle overflow as well. Overload the `/` operator to divide one `Int` object by
another. Print a warning and terminate the program if division by zero occurs. Implement the
class `Int` to handle overflow by checking the result of arithmetic operations and comparing
it to the valid range for integers. In the `main` function, create `Int` objects and perform
various arithmetic operations, testing the overloads for correctness and handling overflow.

UML Diagram:

Source Code:
#include <iostream>
#include <limits>
#include <cstdlib>

using namespace std;

class Int {
private:
int num;

public:
Int(int num = 0) {
this->num = num;
}

Int(const Int& h) {
this->num = h.num;
}

~Int() {}

void setNum(int num) { this->num = num; }

int getNum() const { return num; }

Int operator+(const Int& h) const {


if (additionOverflow(this->num, h.num)) {
throw overflow_error("Addition overflow detected!");
}
return Int(this->num + h.num);
}

Int operator-(const Int& h) const {


if (subtractionOverflow(this->num, h.num)) {
throw overflow_error("Subtraction overflow detected!");
}
return Int(this->num - h.num);
}

Int operator*(const Int& h) const {


if (multiplicationOverflow(this->num, h.num)) {
throw overflow_error("Multiplication overflow
detected!");
}
return Int(this->num * h.num);
}

Int operator/(const Int& h) const {


if (divisionOverflow(this->num, h.num)) {
throw overflow_error("Division by zero detected!");
}
return Int(this->num / h.num);
}

void Display() const {


cout << num << endl;
}
private:
bool additionOverflow(int a, int b) const {
return (a > 0 && b > INT_MAX - a) || (a < 0 && b < INT_MIN - a);
}

bool subtractionOverflow(int a, int b) const {


return (b > 0 && a < INT_MIN + b) || (b < 0 && a > INT_MAX + b);
}

bool multiplicationOverflow(int a, int b) const {


if (a == 0 || b == 0) return false;
if (a > 0) {
if (b > 0 && a > INT_MAX / b) return true;
if (b < 0 && a > INT_MIN / b) return true;
}
else {
if (b > 0 && a < INT_MIN / b) return true;
if (b < 0 && a < INT_MAX / b) return true;
}
return false;
}

bool divisionOverflow(int a, int b) const {


return b == 0 || (a == INT_MIN && b == -1);
}
};

// Overloading << operator


ostream& operator<<(ostream& out, const Int& obj) {
out << obj.getNum();
return out;
}

// Overloading >> operator


istream& operator>>(istream& in, Int& obj) {
int temp;
in >> temp;
obj.setNum(temp);
return in;
}

int main() {
// Test addition within range
Int obj1(100);
Int obj2(200);
Int sum = obj1 + obj2;
cout << "Sum within range: "; sum.Display();

// Test addition causing overflow


Int obj3(INT_MAX);
Int obj4(1);
try {
Int sumOverflow = obj3 + obj4;
cout << "Sum causing overflow: "; sumOverflow.Display();
}
catch (const std::exception & e) {
cerr << e.what() << endl; // Report the error
}
// Test subtraction resulting in non-negative value
Int obj5(50);
Int obj6(20);
Int diff = obj5 - obj6;
cout << "Subtraction resulting in non-negative value: ";
diff.Display();

// Test multiplication within range


Int obj7(1000);
Int obj8(3);
Int prod = obj7 * obj8;
cout << "Multiplication within range: "; prod.Display();

// Test multiplication causing overflow


Int obj9(INT_MAX);
Int obj10(2);
try {
Int prodOverflow = obj9 * obj10;
cout << "Multiplication causing overflow: ";
prodOverflow.Display();
}
catch (const std::exception & e) {
cerr << e.what() << endl; // Report the error
}

// Test division resulting in valid output


Int obj11(100);
Int obj12(5);
Int quot = obj11 / obj12;
cout << "Division resulting in valid output: "; quot.Display();

// Test division by zero


Int obj13(100);
Int obj14(0);
try {
Int quotZero = obj13 / obj14;
cout << "Division by zero: "; quotZero.Display();
}
catch (const std::exception & e) {
cerr << e.what() << endl; // Report the error
}

return 0;
}

Output:
3. Create a C++ class called Polynomial that uses a dynamic array to store coefficients, with
each index representing the power of the variable. Implement a constructor for initializing the
polynomial and a display() method for printing it in a readable format. Overload the +, -, and
* operators for adding, subtracting, and multiplying polynomial objects, ensuring results are
simplified by removing any zero-coefficient terms. In the main() function, create polynomial
objects, perform arithmetic operations, and display the results.

UML Diagram:

Source Code:

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

class Polynomial {
private:
vector<int> coeff; // Vector to store coefficients
vector<int> degree; // Vector to store degrees

public:
// Default and Parameterized Constructor
Polynomial(int inputs = 3, const int* coeffi = nullptr, const int*
degre = nullptr) {
if (inputs < 3) {
inputs = 3;
}
if (coeffi != nullptr && degre != nullptr) {
for (int i = 0; i < inputs; ++i) {
coeff.push_back(coeffi[i]);
degree.push_back(degre[i]);
}
}
else {
for (int i = 0; i < inputs; ++i) {
degree.push_back(i);
coeff.push_back(1); // Default coefficients
}
}
}

// Add two polynomials


Polynomial operator+(const Polynomial& b) const {
Polynomial result;

// Combine coefficients for the same degree


for (size_t i = 0; i < coeff.size(); ++i) {
result.coeff.push_back(coeff[i]);
result.degree.push_back(degree[i]);
}
for (size_t j = 0; j < b.coeff.size(); ++j) {
bool found = false;
for (size_t k = 0; k < result.degree.size(); ++k) {
if (result.degree[k] == b.degree[j]) {
result.coeff[k] += b.coeff[j];
found = true;
break;
}
}
if (!found) {
result.coeff.push_back(b.coeff[j]);
result.degree.push_back(b.degree[j]);
}
}
return result;
}

// Subtract two polynomials


Polynomial operator-(const Polynomial& b) const {
Polynomial result;

// Combine coefficients for the same degree


for (size_t i = 0; i < coeff.size(); ++i) {
result.coeff.push_back(coeff[i]);
result.degree.push_back(degree[i]);
}
for (size_t j = 0; j < b.coeff.size(); ++j) {
bool found = false;
for (size_t k = 0; k < result.degree.size(); ++k) {
if (result.degree[k] == b.degree[j]) {
result.coeff[k] -= b.coeff[j];
found = true;
break;
}
}
if (!found) {
result.coeff.push_back(-b.coeff[j]);
result.degree.push_back(b.degree[j]);
}
}
return result;
}

// Multiply two polynomials


Polynomial operator*(const Polynomial& b) const {
Polynomial result;

// Multiply coefficients and add degrees


for (size_t i = 0; i < coeff.size(); ++i) {
for (size_t j = 0; j < b.coeff.size(); ++j) {
int newCoeff = coeff[i] * b.coeff[j];
int newDegree = degree[i] + b.degree[j];
bool found = false;
for (size_t k = 0; k < result.degree.size(); ++k) {
if (result.degree[k] == newDegree) {
result.coeff[k] += newCoeff;
found = true;
break;
}
}
if (!found) {
result.coeff.push_back(newCoeff);
result.degree.push_back(newDegree);
}
}
}
return result;
}

// Evaluate the polynomial at a given value of x


int evaluate(int x) const {
int result = 0;
for (size_t i = 0; i < coeff.size(); ++i) {
result += coeff[i] * pow(x, degree[i]);
}
return result;
}

// Display the polynomial


void show() const {
for (size_t i = 0; i < coeff.size(); ++i) {
if (coeff[i] != 0) { // Skip zero coefficients
cout << coeff[i] << "x^" << degree[i];
if (i != coeff.size() - 1) {
cout << " + ";
}
}
}
cout << endl;
}
};
int main() {
int coeff1[] = { 5, -3, 4 }; // Coefficients for polynomial 1
int degree1[] = { 2, 1, 0 }; // Degrees for polynomial 1

int coeff2[] = { 2, 0, -1 }; // Coefficients for polynomial 2


int degree2[] = { 2, 1, 0 }; // Degrees for polynomial 2

Polynomial poly1(3, coeff1, degree1);


Polynomial poly2(3, coeff2, degree2);

cout << "Polynomial 1: ";


poly1.show(); // Displaying polynomial 1

cout << "Polynomial 2: ";


poly2.show(); // Displaying polynomial 2

Polynomial sum = poly1 + poly2;


cout << "Result of Addition: ";
sum.show(); // Displaying the sum of polynomials

Polynomial difference = poly1 - poly2;


cout << "Result of Subtraction: ";
difference.show(); // Displaying the difference of polynomials

Polynomial product = poly1 * poly2;


cout << "Result of Multiplication: ";
product.show(); // Displaying the product of polynomials

int x = 2;
cout << "Evaluating Polynomial 1 at x = " << x << ": " <<
poly1.evaluate(x) << endl; // Evaluating polynomial 1 at x

return 0;
}

Output:
complex(double r, double
i):re(r), im(i)
{}
void show()
{
cout<<"complex number:
"<<re<<"+"<<im<<"i"<<endl;
}
complex operator +
(complex rhs)
{
complex temp;
temp.re=re + rhs.re;
temp.im=im + rhs.im;
return temp;
}
};
void main()
{
complex c1(3, 4.3), c2(2, 4);
c1.show();
c2.show();
complex c3;
c3=c1+ c2; //Invocation
of "+" Operator -- direct
//or
//c3=c1.operator+ (c2);
//Invocation of "+" Operator --
Function
c3.show();
}
Lab No.4 Operator
Overloading
4.1 Objectives of the lab:
Introducing the concepts of
operator overloading and
overloading different operators
such as
14 Arithmetic operators
15 Relational operators
16 Logical operators
17 Unary operators

You might also like