OOPPRAC1
OOPPRAC1
❖ Software Requirements: 64-bit Open source Linux or its derivative, Open Source
C++ Programming tool like G++/GCC.
❖ Hardware Requirements: Pentium IV, 512 RAM.
❖ Theory- Concept:
You can redefine or overload most of the built-in operators available in C++. Thus a programmer
can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a
return type and a parameter list.
Syntax:
Return_type operator op (arg-list)
Eg. complex operator+ (complex obj);
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
return 0;
}
2. Binary Operator:
Overloading with a single parameter is called binary operator overloading. Similar to unary
operators, binary operators can also be overloaded. Binary operatorsrequire two operands,
and they are overloaded by using member functions and friend functions.
Example:
using namespace std;
class temp
{
complex operator + (complex c2)
{
complex c3;
c3.x = x + c2.x;
c3.y = y + c2.y;
return c3;
}
};
❖ Algorithm:
1. Start.
2. Create class complex with data members real and imag, and member functions operator
+, operator * for overloading operators +,*,friend functions for << and >> to print and
read Complex Numbers.
3. Inside class define default constructor to initialize variables to 0+0i.
4. Define operator overloaded functions to add, multiply,<< and >> two complex numbers.
5. Create 3 objects c1, c2, c3 in main().
6. Get choice from user to get complex numbers, addition, multiplication and quit.
7. If choice 1 then call the operator overloading function >> and get two complex numbers.
Display complex numbers by calling operator overloading function << If choice 2 then
c3=c1+c2; to invoke the overloaded + operator. Call overloaded << operator to display
the result.
8. If choice 3 then c3=c1*c2; to invoke the overloaded * operator. Call overloaded <<
operator to display the result.
9. If choice 4 then exit.
10. Stop.