Week 6 Operator Over
Week 6 Operator Over
Week 6
Lecture 1 & 2
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.
Condition operator ( ?: )
Page 1 of 9
Object Oriented Programming
Category Operators
Airthmetic +,–,*,/,%
Logical || , && , !
Assignment =
Unary ++ , —
Subscripting []
Deference *
Function call ()
Address of &
Page 2 of 9
Object Oriented Programming
Comma ,
Example:
Assume that class Distance takes two member object i.e. feet and inches, create a function by
Page 3 of 9
Object Oriented Programming
which Distance object should decrement the value of feet and inches by 1 (having single
operand of Distance Type).
#include <iostream>
class Distance {
public:
// Member Object
Distance(int f, int i)
this->feet = f;
this->inch = i;
void operator-()
feet--;
inch--;
Page 4 of 9
Object Oriented Programming
cout << "\nFeet & Inches(Decrement): " << feet << "'" << inch;
};
// Driver Code
int main()
-d1;
return 0;
Output:
In the above program, it shows that no argument is passed and no return_type value is returned,
because unary operator works on a single operand. (-) operator change the functionality to its
member function.
Note: d2 = -d1 will not work, because operator-() does not return any value.
Page 5 of 9
Object Oriented Programming
Let’s take the same example of class Distance, but this time, add two distance objects.
#include <iostream>
class Distance {
public:
// Member Object
// No Parameter Constructor
Distance()
this->feet = 0;
this->inch = 0;
// Parametrized Constructor
Distance(int f, int i)
this->feet = f;
Page 6 of 9
Object Oriented Programming
this->inch = i;
Distance d3;
return d3;
};
// Driver Code
int main()
Page 7 of 9
Object Oriented Programming
Distance d3;
d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
Output:
Page 8 of 9
Object Oriented Programming
Page 9 of 9