0% found this document useful (0 votes)
8 views18 pages

Week 11 Lec 01 - Operator Overloading

This lecture on Operator Overloading in Object-Oriented Programming discusses how to enhance the functionality of C++ operators for user-defined data types, making code more readable. It covers examples of overloading unary and binary operators, including increment and addition, as well as implementing safety features like bounds checking with the overloaded [] operator. The lecture concludes with notes on the requirements and considerations for operator overloading.

Uploaded by

dawoodtaswar390
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Week 11 Lec 01 - Operator Overloading

This lecture on Operator Overloading in Object-Oriented Programming discusses how to enhance the functionality of C++ operators for user-defined data types, making code more readable. It covers examples of overloading unary and binary operators, including increment and addition, as well as implementing safety features like bounds checking with the overloaded [] operator. The lecture concludes with notes on the requirements and considerations for operator overloading.

Uploaded by

dawoodtaswar390
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

CS1004 – Object

Oriented Programming
Lecture # 16
Wednesday, April 14, 2022
Spring 2022
FAST – NUCES, Faisalabad Campus

Muhammad Yousaf
2
Operator Overloading

CS1004 - Objected Oriented Programming


3 Operator Overloading
 One of the most exciting feature of OOP
 Transforms complex function calls to obvious ones
 Example
 d3.addobjects(d1, d2);
OR
 d3 = d1.addobjects(d2);
 Converted to a much more readable
 d3 = d1 + d2;
 Gives normal C++ operators +, -, ++, <= and >=
additional meaning when applied to user-defined data
types
CS1004 - Objected Oriented Programming
4 Overloading Unary Operator pre-increment (++)
class Counter int main()
{ {
private: Counter c1, c2; //define and
unsigned int count; //count initialize

public: cout << “\nc1 = ” <<


c1.get_count(); cout << “\nc2 = ” <<
Counter() : count(0){} c2.get_count();
//constructor
++c1; //increment c1
unsigned int get_count(){ //return
count ++c2; //increment c2
return count; ++c2; //increment c3
} cout << “\nc1 = ” <<
c1.get_count(); cout << “\nc2 = ” <<
void operator ++(){//increment
c2.get_count()
(prefix)
++count; << endl;

} return 0;

}; }
CS1004 - Objected Oriented Programming
5 Overloading Unary Operator pre-increment (++)
 The code in the last slide does not allow the int main()
following statement to execute {
 c1 = ++c2; Counter c1, c2;
 cout << "\nc1 = " <<
Because the return type is void
c1.get_count(); cout << "\nc2 =
 To overcome this problem " << c2.get_count();
Counter operator ++ ()
++c1; //increment c1
{
++count; //increment count c2 = ++c1;
Counter temp; //make a temporary
//Counter
cout << "\nc1 = " <<
c1.get_count();
temp.count = count; //give it same cout << "\nc2 = " <<
//value as this c2.get_count()
obj << endl;
return temp; //return the copy return 0;
}
}

CS1004 - Objected Oriented Programming


6 Nameless Temporary Objects
Counter operator ++ ()  By adding overloaded constructor and
new definition of ++
{
Counter(int c):count(c)
++count; //increment count
//constructor
Counter temp; //make a
{ }
temporary
Counter operator ++() //increment
//
count
Counter
{
temp.count = count; //give
it same ++count; // increment count
//value //return an unnamed
as this obj temporary //object
return temp; //return the return Counter(count);
copy }
}
CS1004 - Objected Oriented Programming

 Can be made more convenient to


7 Post-increment Counter++
//increment count (postfix) int main()
{
Counter operator ++ (int)
Counter c1, c2;
{ cout << "\nc1 = " << c1.get_count();
//return an unnamed cout << "\nc2 = " << c2.get_count();
temporary ++c1; //increment c1
return Counter(count++); c2 = ++c1;
cout << "\nc1 = " << c1.get_count();
//object initialized to
cout << "\nc2 = " << c2.get_count()
this << endl;
//count, then increment c2 = c1++;
count cout << "\nc1 = " << c1.get_count();
} cout << "\nc2 = " << c2.get_count()
<< endl;
return 0;
}

CS1004 - Objected Oriented Programming


8 Pre and post increment
 Pre-increment
 Counter operator ++ () //increment count (prefix)
 Post-increment
 Counter operator ++ (int) //increment count
(postfix)
 The only different is int in the parenthesis
 It is not actually a parameter
 Just a signal to compiler to create post-increment

CS1004 - Objected Oriented Programming


9 Pre and post decrement
 Pre-increment
 Counter operator -- () //decrement count (prefix)
 Post-increment
 Counter operator -- (int) //decrement count
(postfix)

CS1004 - Objected Oriented Programming


10
Overloading Binary Operators
Arithmetic Operators

CS1004 - Objected Oriented Programming


11 Performing sum of two objects
class Distance //English Distance class void Distance::sum(Distance d1, Distance d2){
{ feet = d1.feet + d2.feet;
private: inches = d1.inches + d2.inches;
int feet; if (inches >= 12.0) //if total exceeds 12.0,
float inches; { //then decrease inches
public: //constructor (no args) inches -= 12.0; //by 12.0 and
Distance() : feet(0), inches(0.0) { } feet++; //increase feet by 1
//constructor (two args) }
}
Distance(int ft, float in) : feet(ft),
int main()
inches(in) { }
{
void showdist() const //display distance
Distance dist1, dist2, dist3;
{
dist1.getdist();
cout << feet << "' - "
Distance dist2(11, 6.25);
<< inches << '"’;
dist3.sum(dist1, dist2);
}
dist3 = dist1 + dist2; //single ‘+’ operator
void getdist() //get length from user
cout << "dist1 = "; dist1.showdist(); cout <<
{ endl;
cout << "\nEnter feet : "; cin >> feet; cout << "dist2 = "; dist2.showdist(); cout <<
cout << "Enter inches : "; cin >> inches; endl;
} cout << "dist3 = "; dist3.showdist(); cout <<
Distance sum(Distance d1, Distance d2); endl;
}; return 0;
}
CS1004 - Objected Oriented Programming
12 Performing sum of two objects using Overloaded +
class Distance //English Distance class Distance Distance::operator + (Distance d2) const
{ //return sum
private: {
int feet; int f = feet + d2.feet; //add the feet
float inches; float i = inches + d2.inches; //add the
public: inches
Distance() : feet(0), inches(0.0){ } if (i >= 12.0) //if total exceeds 12.0,
Distance(int ft, float in) : feet(ft), { //then decrease inches
inches(in){ } i -= 12.0; //by 12.0 and
void getdist() //get length from user f++; //increase feet by 1
{ } //return a temporary Distance
cout << "\nEnter feet : "; cin >> return Distance(f, i); //initialized to sum
feet; }
cout << "Enter inches : "; cin >> int main()
inches; {
} Distance dist1, dist3, dist4; //define
void showdist() const //display distance distances
{ dist1.getdist(); //get dist1 from user
cout << feet << "' - " << inches Distance dist2(11, 6.25); //define,
<< '“’; initialize dist2
} dist3 = dist1 + dist2; //single ‘+’ operator
Distance operator + (Distance) const; //add 2 dist4 = dist1 + dist2 + dist3; //multiple ‘+’
distances operators
}; cout << "dist1 = "; dist1.showdist(); cout <<
CS1004 - Objected Oriented Programming
endl;
cout << "dist2 = "; dist2.showdist(); cout <<
endl;
13 Redefining + as concatenation in Strings
class String{
int main()
enum {SZ=80}; //static const int SZ = 80;
char str[SZ]; {
public:
String s1 = "\nHello";
String() { strcpy(str, ""); }
String(char st[]) { strcpy(str, st); } String s2 = " World!";
void display() const{ cout << str; }
String s3;
String operator +(String st) const {
String temp; s1.display();
if (strlen(str) + strlen(st.str) < SZ)
s2.display();
{
strcpy(temp.str, str); s3.display();
strcat(temp.str, st.str);
s3 = s1 + s2; //add s2 to s1,
}
else //assign to s3
{
cout << "\nString overflow";
s3.display(); //display s3
exit(1); cout << endl;
}
return temp;
return 0;
} }
};
CS1004 - Objected Oriented Programming
14 Comparison operators <
 Adding a new < overloaded int main()
{
function to the Distance Distance dist1, dist3, dist4;

class dist1.getdist();
Distance dist2(11, 6.25);
if (dist1 < dist2)
bool Distance::operator < cout << "\ndist1 is less than"
<< "dist2";
(Distance dt) const
else
{ cout << "\ndist1 is greater than"
float d1 = feet + inches / << " (or equal to) dist2";
12; cout << endl;
float d2 = dt.feet + cout << "dist1 = ";
dt.inches / 12; dist1.showdist();
return (d1 < d2)?true : cout << endl;
cout << "dist2 = ";
false;
dist2.showdist();
} cout << endl;
}

CS1004 - Objected Oriented Programming


15 Arithmetic assignment Operator +=
 To implement += we have two options  To overcome this issue we have to introduce a
void Distance::operator +=(Distance d) different += overloaded function
{ Distance& Distance::operator +=(Distance d)
feet += d.feet; {
inches += d.inches; feet += d.feet;
if (inches > 12)
inches += d.inches;
{
feet++; if (inches > 12)
inches -= 12; {
} feet++;
} inches -= 12;
}
 We will be able to execute
return *this;
dist2 += dist1; }
 Now we’ll be able to execute
 But the instruction below will be a
dist2 += dist1;
syntax error  As well as
(dist3 += dist1) += dist2; (dist3 += dist1) += dist2;

CS1004 - Objected Oriented Programming


16 Overloading [] operator
 To implement a safe array that takes care of int main()
array out of bound problem we can implement
overloaded [] operator
{
const int LIMIT = 100; safearay arr;
for (int i = 0; i < LIMIT; ++i)
class safearay arr[i] = i * 10;
{
private:
int arr[LIMIT]; for (int i = 0; i < LIMIT; ++i)
public: cout << "Element " << i
int& operator[](int n)
<< " = " << arr[i]
{
if (n< 0 || n >= LIMIT)
<< endl;
{ return 0;
cout << "\nIndex out of }
bounds";
exit(1);
}  We need to return the reference
return arr[n]; because array can be used at the left
}
}; side of assignment operator as well
CS1004 - Objected Oriented Programming
17 Notes about operator Overloading
 An overloaded operator always requires one less
argument than its number of operands
 one operand is the object of which the operator is a
member

CS1004 - Objected Oriented Programming


18 Questions

CS1004 - Objected Oriented Programming

You might also like