Professional Documents
Culture Documents
Oop Lab 5
Oop Lab 5
Oop Lab 5
EXPERIMENT NO 5
Objective:
LAB ASSESSMENT:
Attributes Excellent Good Average Satisfact Unsatisfact
(5) (4) (3) ory (2) ory (1)
Ability to Conduct
Experiment
Ability to assimilate
the results
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 5
Operator Overloading
Objectives
In this lab students will learn to overload,
➢ Arithmetic operators
➢ Relational operators
➢ Logical operators
➢ Unary operators
Equipment required
Operator Overloading
The process of defining additional meaning of operators is known as Operator Overloading. It
enables the operator to perform different operations depending on the type of operands. It also
enables the operators to process the user-defined data types.
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 own operator meaning to a class by overloading the built-in operator to
perform some specific computation when the operator is used on objects of that class. The
following set of operators is commonly overloaded for user-defined classes:
• = (assignment operator)
• +, -, *, \, (binary arithmetic operators)
• +=, -=, *=, (compound assignment operators)
• ==, !=, >, <, >=, <=, (comparison operators)
Syntax
Return_type: It indicates the type of value returned by the member function Operator: It is a
keyword that indicates that the member function is used to overload an opertor Op: It is the
symbol of operator to be overloaded e.g +,-, ++ etc
Example: Write a program that overloads prefix increment operator to work with user-defined
objects
Overloading Unary Operators
Operator Overloading example
count()
{
n=0;
}
void show(){
cout<<"count is"<<n<<endl;
}
//operator overloading
void operator ++()
{
n=n+1;
}
};
void show(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
Add operator +(Add p)
{
Add temp;
temp.a=p.a+a;
temp.b=p.b+b;
return temp;
}};
In Lab Tasks
Q 1. Write a program that overloads postfix increment operator to work with user-defined objects.
Q 2. Write a program that overloads arithmetic addition operator + for concatenating two string
values.
Q 3. Write a program that overloads addition operator to add two complex numbers
Q 4. Write a program that overloads the comparison operators == to work with String class. The
result of comparison must be 1 if two strings are of same length and 0 otherwise.
• An overloaded operator / for division of two rational numbers. If fraction a/b is divided
by the fraction c/d, the result is
• An overloaded relational operator >= should return a variable of type bool to indicate
whether 1st fraction is greater than or equal to 2nd or not
• Overloaded equality operator == should return a variable of type bool to indicate
whether 1st fraction is equal to the 2nd fraction or not.