Practical No 1,2.OOP
Practical No 1,2.OOP
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:
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.
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
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
Algorithm:
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:
ubuntu@user:~$ ./a.out
Complex Number 1 : 2 + 3i
Complex Number 2 : 3 + 4i
**********MENU**********
3. Exit
Addition : 5 + 7i
Complex Number 1 : 2 + 3i
Complex Number 2 : 3 + 4i
**********MENU**********
3. Exit
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?
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:
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:
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>
public:
Publication(string t, float p, int c) : title(t), price(p), copies(c) {}
public:
Book(string t, float p, int c, string a) : Publication(t, p, c), author(a) {}
void displayBookDetails() {
cout << "Book: " << title << ", Author: " << author << ", Price: $" << price << ", Copies: "
<< copies << endl;
}
};
public:
Magazine(string t, float p, int c, int issue) : Publication(t, p, c), currentIssue(issue) {}
void displayMagazineDetails() {
cout << "Magazine: " << title << ", Current Issue: " << currentIssue << ", Price: $" << price
<< ", Copies: " << copies << endl;
}
int main() {
// Creating book and magazine objects
Book b1("C++ Programming", 29.99, 100, "Bjarne Stroustrup");
Magazine m1("Tech Monthly", 5.99, 50, 2024);
// 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
1. Ordering Copies:
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.