0% found this document useful (0 votes)
42 views19 pages

Lecture9 - Creating New Definitions For Operators

This document discusses operator overloading in C++. It begins by stating the objectives and learning outcomes, which are to understand the exciting features of object-oriented programming and apply user-defined data types using operator overloading. It then explains that operator overloading allows operators to be redefined for user-defined types, making code more readable. It provides examples of overloading unary operators like increment (++) and decrement (--) as well as binary operators like addition (+). The document demonstrates overloading these operators for a sample Counter and Distance class.

Uploaded by

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

Lecture9 - Creating New Definitions For Operators

This document discusses operator overloading in C++. It begins by stating the objectives and learning outcomes, which are to understand the exciting features of object-oriented programming and apply user-defined data types using operator overloading. It then explains that operator overloading allows operators to be redefined for user-defined types, making code more readable. It provides examples of overloading unary operators like increment (++) and decrement (--) as well as binary operators like addition (+). The document demonstrates overloading these operators for a sample Counter and Distance class.

Uploaded by

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

CST-12102

Programming in C++

Lecture 9

Creating New Definitions for Operators


Faculty of Computer Science 1
Objectives

• To know the most exciting features of object-oriented programming


• To apply user-defined data type - operator

Faculty of Computer Science 2


Learning Outcomes

Student can
▪ know the most exciting features of object-oriented programming
▪ apply user-defined data type – operator
▪ create operator overloading function

Faculty of Computer Science 3


Operator Overloading

▪ Operator overloading is one of the most exciting features of


object-oriented programming
▪ For example, statements like
d3.addobjects(d1, d2); OR
d3=d1.addobjects(d2);
▪ can be changed to the much more readable
d3 = d1 + d2;
Here is a list of all the operators that can be overloaded:

Faculty of Computer Science 4


Operator Overloading Cont’d

• the opportunity to redefine the C++ language


• to create new definitions for operators
• Using the operator Keyword followed by the operator sign that
we want to overload.
• data type conversion, is closely connected with operator
overloading

– Overloading Unary Operators


– Overloading Binary Operators

Faculty of Computer Science 5


Overloading Unary Operators

• Unary operators acts on only one operand.


• unary operators are the increment and decrement operators ++
and - -.

c1.inc_count(); // by calling function inc_count()

Class ‘s
instance
++c1; // by using increment operator ++

Faculty of Computer Science 6


Overloading Unary Operators - Example
// Page 321
// countpp1.cpp int main()
// increment counter variable {
with ++ operator(prefix) Counter c1, c2;
#include <iostream.h> cout << “\nc1=” << c1.get_count();
class Counter
cout << “\nc2=” << c2.get_count();
{
private: ++c1;
unsigned int count; ++c2;
public: ++c2;
Counter() : count(0) cout << “\nc1=” << c1.get_count();
{}
cout << “\nc2=” << c2.get_count() <<
unsigned int get_count()
endl;
{ return count; }
void operator ++ () return 0;
{ }
++count;
}
}; Faculty of Computer Science 7
Overloading Unary Operators – Example
// Page 324 Counter operator ++ ()
// countpp2.cpp {
++count;
// increment counter variable Counter temp;
with ++ operator, return value temp.count = count;
#include <iostream.h> return temp;
class Counter }
{ };
int main()
private: {
unsigned int count; Counter c1, c2; //c1=0, c2=0
public: cout << “\nc1=” << c1.get_count();
Counter() : count(0) cout << “\nc2=” << c2.get_count();
{} ++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
unsigned int get_count() cout << “\nc1=” << c1.get_count();
{ return count; } cout << “\nc2=” << c2.get_count() << endl;
return 0;
}
Faculty of Computer Science 8
Overloading Unary Operators – Example
// Page 325 Counter operator ++ ()
// countpp3.cpp {
// increment counter variable ++count; // increment count, then return
with ++ operator return Counter(count); // an unnamed temporary
//object initialized to this count
// uses unnamed temporary
}
object
};
#include <iostream.h>
int main()
class Counter
{ {
private: Counter c1, c2; //c1=0, c2=0
unsigned int count; cout << “\nc1=” << c1.get_count();
public: cout << “\nc2=” << c2.get_count();
Counter() : count(0) ++c1; //c1=1
{}
c2 = ++c1; //c1=2, c2=2
Counter(int c) : count(c)
cout << “\nc1=” << c1.get_count();
{}
unsigned int get_count() cout << “\nc2=” << c2.get_count() << endl;
{ return 0;
return count; }
Faculty of Computer Science 9
}
Overloading Unary Operators – Example
//Page 327 Counter operator ++ (int) //increment count (postfix)
// postfix.cpp {
// overloaded ++ operator in both return Counter(count++);
}
prefix and postfix
};
#include <iostream.h>
class Counter int main()
{ {
private: Counter c1, c2; //c1=0, c2=0
unsigned int count; cout << “\nc1=” << c1.get_count();
public: cout << “\nc2=” << c2.get_count();
Counter() : count(0) ++c1; //c1=1
{} c2 = ++c1; //c1=2, c2=2 (prefix)
cout << “\nc1=” << c1.get_count();
Counter(int c) : count(c)
cout << “\nc2=” << c2.get_count();
{} c2 = c1++; //c1=3, c2=2 (postfix)
unsigned int get_count() const cout << “\nc1=” << c1.get_count();
{ return count; } cout << “\nc2=” << c2.get_count() << endl;
Counter operator ++ () //increment return 0;
{ count (prefix) }
return Counter(++count);
Faculty of Computer Science 10
}
Overloading Binary Operators
• Binary operators can be overloaded just as easily as unary
operators
• Overload arithmetic operators, comparison operators, and
arithmetic assignment operators
• In the operator + () function, the left operand is accessed
directly—since this is the object of which the operator is a
member—using feet and inches.
• The right operand is accessed as the function’s argument, as
d2.feet and d2.inches.

Faculty of Computer Science 11


Overloading Binary Operators – Example
//Page 329 Distance Distance::operator + (Distance d2)
// englplus.cpp { int f = feet + d2.feet;
// overloaded ‘+’ operator adds two Distances float i = inches + d2.inches;
#include <iostream> if(i >= 12.0)
class Distance {i -= 12.0;
{ f++;
private: } //return a temporary Distance
int feet; return Distance(f,i); //initialized to sum
}
float inches;
int main()
public:
{
Distance() : feet(0),inches(0.0){ } Distance dist1, dist3, dist4;
Distance(int ft, float in) :feet(ft),inches(in) dist1.getdist();
{} Distance dist2(11, 6.25);
void getdist() dist3 = dist1 + dist2; //single ‘+’ operator
{cout << “\nEnter feet: “; cin >> feet; dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators
cout << “Enter inches: “; cin >> inches;} cout << “dist1 = “; dist1.showdist(); cout << endl;
void showdist() const cout << “dist2 = “; dist2.showdist(); cout << endl;
{ cout << feet << “\’-” << inches << ‘\”’;} cout << “dist3 = “; dist3.showdist(); cout << endl;
cout << “dist4 = “; dist4.showdist(); cout << endl;
Distance operator + ( Distance );
return 0;
}; }
Faculty of Computer Science 12
13
Faculty of Computer Science
Overloading Binary Operators – Example
Comparison Operators //compare this distance with d2
// engless.cpp bool Distance::operator < (Distance d2)
// overloaded ‘<’ operator compares two Distances {
#include <iostream> float bf1 = feet + inches/12;
using namespace std; float bf2 = d2.feet + d2.inches/12;
class Distance //English Distance class return (bf1 < bf2) ? true : false;
{private: }
int main()
int feet;
{
float inches;
Distance dist1; //define Distance dist1
public: //constructor (no args) dist1.getdist(); //get dist1 from user
Distance() : feet(0), inches(0.0) Distance dist2(6, 2.5);
{ } //constructor (two args) cout << “\ndist1 = “; dist1.showdist();
Distance(int ft, float in) : feet(ft), inches(in) cout << “\ndist2 = “; dist2.showdist();
{} if( dist1 < dist2 ) //overloaded ‘<’ operator
void getdist() //get length from user cout << “\ndist1 is less than dist2”;
{cout << “\nEnter feet: “; cin >> feet; else
cout << “\ndist1 is greater than (or equal to)
cout << “Enter inches: “; cin >> inches;}
dist2”;
void showdist() const //display distance
cout << endl;
{ cout << feet << “\’-” << inches << ‘\”’; } return 0;
bool operator < (Distance); } Science
Faculty of Computer 14
Overloading Binary Operators – Example
Arithmetic Assignment Operators void Distance::operator += (Distance d2)
// englpleq.cpp {
// overloaded ‘+=’ assignment operator feet += d2.feet; //add the feet
inches += d2.inches; //add the inches
#include <iostream.h>
if(inches >= 12.0) //if total exceeds 12.0,
class Distance
{ //then decrease inches
{private: inches -= 12.0; //by 12.0 and
int feet; feet++; //increase feet
float inches; } //by 1
public: Distance() : feet(0), inches(0.0) }
{ } //constructor (two args) int main()
Distance(int ft, float in) : feet(ft), inches(in) {Distance dist1; //define dist1
{} dist1.getdist(); //get dist1 from user
cout << “\ndist1 = “; dist1.showdist();
void getdist() //get length from user
Distance dist2(11, 6.25);
{cout << “\nEnter feet: “; cin >> feet;
cout << “\ndist2 = “; dist2.showdist();
cout << “Enter inches: “; cin >> inches;} dist1 += dist2; //dist1 = dist1 + dist2
void showdist() //display distance cout << “\nAfter addition,”;
{ cout << feet << “\’-” << inches << ‘\”’; } cout << “\ndist1 = “; dist1.showdist();
void operator += ( Distance ); cout << endl;
}; return 0;
Faculty of Computer}Science 15
Concatenating Strings {
// strplus.cpp String temp; //make a temporary String
// overloaded ‘+’ operator concatenates if( strlen(str) + strlen(ss.str) < SZ )
strings
{strcpy(temp.str, str); //copy this string to temp
#include <iostream.h>
#include <string.h> //for strcpy(), strcat() strcat(temp.str, ss.str); //add the argument string
#include <stdlib.h> //for exit() }
class String else
{ { cout << “\nString overflow”; exit(1); }
private: return temp; } //return temp String
enum { SZ=80 }; };
char str[SZ]; int main()
public: {
String() String s1 = “\nMerry Christmas! “; //uses constructor 2
{ strcpy(str, “”); } String s2 = “Happy new year!”; //uses constructor 2
String( char s[] )
String s3; //uses constructor 1
{ strcpy(str, s); }
s1.display(); s2.display();s3.display();
void display() const
s3 = s1 + s2;
{ cout << str; }
String operator + (String ss) s3.display(); //display s3
cout <<
Faculty of Computer endl;return 0;
Science 16
Summary

• Normal C++ operators can be given new meanings when applied to user-
defined data types.
• The keyword operator is used to overload an operator, and the resulting
operator will adopt the meaning supplied by the programmer.
• Closely related to operator overloading is the issue of type conversion.
• Some conversions take place between user-defined types and basic types.

Faculty of Computer Science 17


Pg 367-369

• 1,2,3,5,6,7

Faculty of Computer Science 18


Faculty of Computer Science 19

You might also like