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

Practical No 1,2.OOP

Uploaded by

Mr. Omkar
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)
95 views

Practical No 1,2.OOP

Uploaded by

Mr. Omkar
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/ 14

Practical No: 1

Title: Arithmetic operations on complex numbers using operator overloading.

Problem Statement:
Implement a class Complex which represents the Complex Number data type. Implement the following
operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >>to print and read Complex Numbers.

Prerequisites:

Object Oriented Programming

Objectives:
To learn the concept of constructor, default constructor, operator overloading using member function
and friend function.
Theory:

Operator Overloading
It is a specific case of polymorphism where different operators have different implementations
depending on their arguments. In C++ the overloading principle applies not only to functions, but to
operators too. That is, of operators can be extended to work not just with built-in types but also classes. A
programmer can provide his or her own operator to a class by overloading the built-in operator to
perform some specific computation when the operator is used on objects of that class.

An Example of Operator Overloading


Complex a(1.2,1.3); //this class is used to represent complex numbers
Complex b(2.1,3); //notice the construction taking 2 parameters for the real and imaginary part
Complex c = a+b; //for this to work the addition operator must be overloaded

Arithmetic Operators
Arithmetic Operators are used to do basic arithmetic operations like addition, subtraction, multiplication,
division, and modulus.
The following table list the arithmetic operators used in C++.

Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division

SVCET, RAJURI 2021-2022


% Modulus

With C++ feature to overload operators, we can design classes able to perform operations using
standard operators. Here is a list of all the operators that can be overloaded:
Over loadable operators

+ - * / = <> += -= *= /= <<>>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= []
5. To overload an operator in order to use it with classes we declare operator functions, which are
regular functions whose names are the operator keyword followed by the operator sign that we
want to overload. The format is:
6. type operator operator-symbol (parameters) {/*...*/ }
7. The operator keyword declares a function specifying what operator-symbol means when
applied to instances of a class. This gives the operator more than one meaning, or "overloads"
it. The compiler distinguishes between the different meanings of an operator by examining the
types of its operands.
Syntax:
return_typeclass_name :: operator op(arg_list)
{
//function body
}
where,
8. Return type is the value returned by the specified operation
9. op is the operator to be overload.
10. op is proceeding by the keyword operator.
11. operator op is the function name
Process of the overloading has 3 steps
1. Create a class that define a data types that is used in the overloading operation
2. Declare the operator function operator op () in the public part of the
class. It may be either a member function or a friend function.
3. Define the operator function to implement the required operation

e.g.
Overloading Binary operators:

A statement like
C = sum (A, B); // functional notation
This functional notation can be replaced by a natural looking expression
C = A+B; // arithmetic notation
by overloading the + operator using an operator+ () function

SVCET, RAJURI 2021-2022


Facilities:

Linux Operating Systems, G++

Algorithm:

Step 1: Start the program


Step 2: Create a class complex
Step 3: Define the default constructor.
Step 4: Declare the operator function which are going to be overloaded and display function
Step 5: Define the overloaded functions such as +, -,/,* and the display function
For Addition:
(a+bi) + (x + yi) = ((a+x)+(b+y)i)
For Multiplication:
(a+bi) * (x + yi) = (((a*x)-(b*y)) + ((a*y) + (x*b))i)
Step 6: Create objects for complex class in main () function
Step 7: Create a menu for addition, multiplication of complex numbersand display the result
Step 8: Depending upon the choice from the user the arithmetic operators will invoke the overloaded
operator automatically and returns the result
Step 9: Display the result using display function.

Input:

Complex numbers with real and imaginary values for two complex numbers.
Example:
Complex No 1: Real Part : 5
Imaginary part : 4
Complex No 2: Real Part : 5
Imaginary part : 4

Output:

Default constructor value=0+0i


Enter the 1st number
Enter the real part2
Enter the imaginary part4
Enter the 2nd number
Enter the real part4
Enter the imaginary part8
The first number is 2+4i
The second number is 4+8i
The addition is 6+12i
The multiplication is -24+32i

SVCET, RAJURI 2021-2022


Practical Program:
# include<iostream>
using namespace std;
class Complex
{
double real;
double img;
public:
Complex();
friend istream & operator >> (istream &, Complex &);
friend ostream & operator << (ostream &, const Complex &);
Complex operator + (Complex);
Complex operator * (Complex);
};
Complex::Complex()
{
real = 0;
img = 0;
}
istream & operator >> (istream &, Complex & i)
{
cin >> i.real >> i.img;
return cin;
}
ostream & operator << (ostream &, const Complex & d)
{
cout << d.real << " + " << d.img << "i" << endl;
return cout;
}
Complex Complex::operator + (Complex c1)
{
Complex temp;
temp.real = real + c1.real;
temp.img = img + c1.img;
return temp;
}
Complex Complex::operator * (Complex c2)
{
Complex tmp;
tmp.real = real * c2.real - img * c2.img;
tmp.img = real * c2.img + img * c2.real;
return tmp;
}
int main()
{
Complex C1, C2, C3, C4;
int flag = 1;
char b;
while (flag == 1)
{
cout << "Enter Real and Imaginary part of the Complex Number 1 : \n";
cin >> C1; 2+4i;
cout << "Enter Real and Imaginary part of the Complex Number 2 : \n";
cin >> C2; 3+2i;
int f = 1;
while (f == 1)
{

SVCET, RAJURI 2021-2022


cout << "Complex Number 1 : " << C1 << endl; 2+4i;
cout << "Complex Number 2 : " << C2 << endl; 3+2i;
cout << "**********MENU**********" << endl;
cout << "1. Addition of Complex Numbers" << endl;
cout << "2. Multiplication of Complex Numbers" << endl;
cout << "3. Exit\n";
int a;
cout << "Enter your choice from above MENU (1 to 3) : ";
cin >> a;
if (a == 1)
{
C3 = C1+C2;
cout << "Addition : " << C3 << endl;
cout << "Do you wan to perform another operation (y/n) : \n";
cin >> b;
if (b == 'y' || b == 'Y')
{
f=1;
}
else
{
cout << "Thanks for using this program!!\n";
flag=0;
f=0;
}
}
else if (a == 2)
{
C4 = C1 * C2;
cout << "Multiplication : " << C4 << endl;
cout << "Do you wan to perform another operation (y/n) : \n";
cin >> b;
if (b == 'y' || b == 'Y')
{
f=1;
}
else
{
cout << "Thanks for using this program!!\n";
flag=0;
f=0;
}
}
else
{
cout << "Thanks for using this program!!\n";
flag=0;
f=0;
}
}
}
return 0;

SVCET, RAJURI 2021-2022


Practical Output:
ubuntu@user:~$ g++ GroupA_Practical1.cpp

ubuntu@user:~$ ./a.out

Enter Real and Imaginary part of the Complex Number 1 :

Enter Real and Imaginary part of the Complex Number 2 :

Complex Number 1 : 2 + 3i

Complex Number 2 : 3 + 4i

**********MENU**********

1. Addition of Complex Numbers

2. Multiplication of Complex Numbers

3. Exit

Enter your choice from above MENU (1 to 3) : 1

Addition : 5 + 7i

Do you wan to perform another operation (y/n) :

Complex Number 1 : 2 + 3i

Complex Number 2 : 3 + 4i

**********MENU**********

1. Addition of Complex Numbers

2. Multiplication of Complex Numbers

3. Exit

Enter your choice from above MENU (1 to 3) : 2

SVCET, RAJURI 2021-2022


Multiplication : -6 + 17i

Do you wan to perform another operation (y/n) :

Thanks for using this program!!

SVCET, RAJURI 2021-2022


Conclusion:

Hence, we have studied concept of operator overloading.

Questions:
1. What is operator overloading?
2. What are the rules for overloading the operators?
3. State clearly which operators are overloaded and which operator are not overloaded?
4. State the need for overloading the operators.
5. Explain how the operators are overloaded using the friend function.
6. What is the difference between “overloading” and “overriding”?
7. What is operator function? Describe the syntax?
8. When is Friend function compulsory? Give an example?

SVCET, RAJURI 2021-2022


Practical No:2

Problem Statement:
Identify commonalities and differences between Publication, Book and Magazine
classes. Title, Price, Copies are common instance variables and saleCopy is common method.
The differences are, Bookclass has author and orderCopies(). Magazine Class has methods
orderQty, Current issue, receiveissue().Write a program to find how many copies of the given
books are ordered and display total sale of publication.

Prerequisites:

Object Oriented Programming.

The provided C++ program effectively illustrates several core concepts of object-oriented
programming (OOP). Here’s a breakdown of these concepts as they relate to the program:

Theory:

1. Classes and Objects

Classes: The program defines three classes: Publication, Book, and Magazine. Each class
encapsulates data (attributes) and behavior (methods).

Objects: In main(), instances of Book and Magazine are created, such as b1 and m1,
demonstrating how classes can be used to create concrete objects.

2. Encapsulation

The attributes of each class (title, price, copies, author, currentIssue) are marked as protected or
private, restricting direct access from outside the class. This encapsulation ensures that the
internal state of objects can only be modified through class methods, promoting data integrity.

3. Inheritance

The Book and Magazine classes inherit from the Publication base class, which allows them to
reuse common functionality (like saleCopy()) and attributes. This establishes an "is-a"
relationship where a Book and a Magazine are types of Publication.

4. Polymorphism
The orderCopies() method in the Publication class is a pure virtual function, making Publication
an abstract class. Both derived classes (Book and Magazine) implement this method in their own
way, demonstrating polymorphism. This allows the program to call orderCopies() on any
Publication object, regardless of its specific type.

5. Method Overriding

The Book and Magazine classes override the orderCopies() method from the Publication class.
This customization lets each class define specific behaviors for how copies are ordered.

6. Method Overloading

The Magazine class has an additional method, orderQty(), which provides a specific
implementation for ordering magazine copies, showcasing method overloading through different
methods fulfilling similar roles.

7. Abstraction

By using a pure virtual function (orderCopies()), the program abstracts the concept of ordering
copies. It provides a common interface for derived classes without implementing the details in
the base class.

8. Dynamic Binding

The program utilizes dynamic binding, particularly with the overridden orderCopies() method.
When the program calls this method on a Publication pointer or reference, the appropriate
derived class version is executed based on the actual object type.

Here is a C++ program that models the problem using object-oriented programming concepts:
Practical Program:

#include <iostream>
#include <string>
#include <strlib>

using namespace std;

// Base class Publication


class Publication {
protected:
string title;
float price;
int copies;

public:
Publication(string t, float p, int c) : title(t), price(p), copies(c) {}

// Common method saleCopy for all publications


void saleCopy(int soldCopies) {
if (soldCopies <= copies) {
copies -= soldCopies;
cout << "Total sale: $" << soldCopies * price << endl;
} else {
cout << "Not enough copies available!" << endl;
}
}

// Pure virtual method to calculate total sale for all publications


virtual void orderCopies(int numCopies) = 0;
};

// Book class inherits Publication


class Book : public Publication {
private:
string author;

public:
Book(string t, float p, int c, string a) : Publication(t, p, c), author(a) {}

// Method to order copies for a book


void orderCopies(int numCopies) override {
copies += numCopies;
cout << numCopies << " copies of the book ordered." << endl;
}

void displayBookDetails() {
cout << "Book: " << title << ", Author: " << author << ", Price: $" << price << ", Copies: "
<< copies << endl;
}
};

// Magazine class inherits Publication


class Magazine : public Publication {
private:
int currentIssue;

public:
Magazine(string t, float p, int c, int issue) : Publication(t, p, c), currentIssue(issue) {}

// Method to order quantity for magazine


void orderQty(int numQty) {
copies += numQty;
cout << numQty << " copies of the magazine ordered." << endl;
}

// Method to receive new issue


void receiveIssue(int newIssue) {
currentIssue = newIssue;
cout << "Magazine updated to issue: " << currentIssue << endl;
}

void displayMagazineDetails() {
cout << "Magazine: " << title << ", Current Issue: " << currentIssue << ", Price: $" << price
<< ", Copies: " << copies << endl;
}

void orderCopies(int numCopies) override {


orderQty(numCopies); // Redirect to orderQty
}
};

int main() {
// Creating book and magazine objects
Book b1("C++ Programming", 29.99, 100, "Bjarne Stroustrup");
Magazine m1("Tech Monthly", 5.99, 50, 2024);

// Ordering copies of books and magazines


b1.orderCopies(20);
m1.orderCopies(30);

// Display details
b1.displayBookDetails();
m1.displayMagazineDetails();

// Selling copies
b1.saleCopy(10); // Selling 10 copies of the book
m1.saleCopy(5); // Selling 5 copies of the magazine

return 0;
}
Output:
20 copies of the book ordered.
30 copies of the magazine ordered.
Book: C++ Programming, Author: Bjarne Stroustrup, Price: $29.99, Copies: 120
Magazine: Tech Monthly, Current Issue: 2024, Price: $5.99, Copies: 80
Total sale: $299.9
Total sale: $29.95

Breakdown of the Output:

1. Ordering Copies:

"20 copies of the book ordered."

"30 copies of the magazine ordered."

2. Displaying Details After Ordering:

For the book: Shows the title, author, price, and updated copies (original 100 + 20 ordered =
120).

For the magazine: Shows the title, current issue, price, and updated copies (original 50 + 30
ordered = 80).

3. Selling Copies:

For the book: Selling 10 copies results in a total sale of $299.90 (10 * 29.99).

For the magazine: Selling 5 copies results in a total sale of $29.95 (5 * 5.99).

.
### Explanation:

- **Publication class (Base Class)**: Contains common attributes like `title`, `price`, and
`copies` with a common method `saleCopy` to handle the sale process. It has a pure virtual
function `orderCopies` to make it an abstract class.

- **Book class (Derived Class)**: Extends the `Publication` class, adding the `author` attribute
and overriding `orderCopies()` method to handle ordering book copies.

- **Magazine class (Derived Class)**: Extends the `Publication` class, adding the `currentIssue`
attribute and additional methods like `orderQty()` and `receiveIssue()`. The `orderCopies()`
method is overridden and internally calls `orderQty()`.

- The `main()` function demonstrates creating objects, ordering copies, selling copies, and
displaying the details of books and magazines.

This program calculates how many copies of books and magazines are ordered and shows the
total sales.

Summary:
This C++ program encapsulates key OOP principles such as encapsulation, inheritance,
polymorphism, method overriding, and abstraction. It effectively models the real-world scenario
of managing publications, allowing for scalability and maintainability as new types of
publications could be easily added by extending the base class.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy