OOP Assignment 6
OOP Assignment 6
Enrollment #: 01-134232-203
Class: BS-CS-2(C)
Objective
This lab session is dedicated to operator overloading in C++. You will learn the syntax of
overloading arithmetic and relational operators and implement them.
Go through Lab 6 of the manual, attempt the given programs and verify their outputs. Once you
are done, perform the following tasks.
Tasks :
4. What is the syntax of overloading ‘*’ operator for a class Matrix. (You do not need to
write the body of the function)
class Matrix {
private:
// Define your matrix data members here
public:
// Constructor(s), destructor, and other member functions
5. Go through example 6.2 of the manual and write the output of the given code segment.
OUTPUT:
6
9
5
Exercise 1
#include <iostream>
class Time {
private:
int hour;
int minute;
public:
Time(int h = 0, int m = 0) : hour(h), minute(m) {}
Time& operator++() {
++minute;
if (minute == 60) {
++hour;
minute = 0;
}
if (hour == 24) {
hour = 0;
}
return *this;
}
Time operator++(int) {
Time temp = *this;
++(*this);
return temp;
}
int main() {
Time T1(12, 30);
Time T2(23, 59);
T3 = ++T1;
std::cout << "After prefix increment (T3 = ++T1): ";
T3.display();
T4 = T2++;
std::cout << "After postfix increment (T4 = T2++): ";
T4.display();
return 0;
}
Exercise 2
Write a class Complex to model complex numbers and overload the following
operators (using member functions).
a. ‘+’ and ‘–‘ operators for addition and subtraction respectively.
b. ‘~’ operator to find the conjugate of a complex number.
c. ‘*’ operator to multiply two complex numbers.
d. ‘!’ operator to find the magnitude (absolute value) of a complex number.
CODE :
#include <iostream>
#include <cmath>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
int main() {
Complex a(3, 4);
Complex b(1, -2);
Complex sum = a + b;
cout << "Sum: ";
sum.display();
Complex diff = a - b;
cout << "Difference: ";
diff.display();
Complex product = a * b;
cout << "Product: ";
product.display();
return 0;
}
OUTPUT :
Exercise 3
Using non-member functions, overload the following operators for the class
Complex.
a. The ‘>’ operator such that the statement c1>c2 should return true if the
real part of c1 is greater than that of c2.
b. The’==’ operator which returns true if the two complex numbers are equal.
CODE :
#include <iostream>
#include <cmath>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
int main() {
Complex c1(3, 4);
Complex c2(5, 2);
Complex c3(3, 4);
cout << "Is c1 > c2? " << (c1 > c2 ? "Yes" : "No") << endl;
cout << "Are c1 and c3 equal? " << (c1 == c3 ? "Yes" : "No") << endl;
return 0;
}
OUTPUT :
Implement the given exercises and get them evaluated by your instructor.
2. Exercise 2
3. Exercuse 3
+++++++++++++++++++++++++