13 operator overloading
TRANSCRIPT
-
8/9/2019 13 Operator Overloading
1/34
Operator OverloadingOperator Overloading
Computer Programming II 1
Lecture 13Lecture 13
-
8/9/2019 13 Operator Overloading
2/34
Computer Programming II #
OverviewOverview Introduction
C++ Operators
Overloadable C++ Operators
Theory of Operator Overloading
Operator Overloading Syntax
-
8/9/2019 13 Operator Overloading
3/34
Computer Programming II #
OverviewOverview
Will you be my friend
Friend example Increment Operator
Parameters & Return Types
Automatic Type Conversion
-
8/9/2019 13 Operator Overloading
4/34
Computer Programming II #
IntroductionIntroduction
Allowing us to use the same function name with different types
and combinations of arguments
Operator Overloading- Similar to function overloading
- Each operators used for several standard types
Example: operator+ operates on int, float and double.
So + is already OverLoaded ( same interface but differentimplementations)
- Adding additional processing power to the operator.
Still remember Function Overloading?
-
8/9/2019 13 Operator Overloading
5/34
Computer Programming II #
-
8/9/2019 13 Operator Overloading
6/34
Computer Programming II #
IntroductionIntroductionExample
// float division operator:
// x
-
8/9/2019 13 Operator Overloading
7/34
-
8/9/2019 13 Operator Overloading
8/34
Computer Programming II #
C++OperatorsC++OperatorsThe taxonomy of the operators can be shown as
follows:
Operators
Unary Binary
x+y
Prefix Postfix
(!, &, ++) ++x (++, --) x++
Accepts one argument
Accepts two arguments
Placed after the argumentPlaced before the argument
-
8/9/2019 13 Operator Overloading
9/34
Computer Programming II #
C++OperatorsC++OperatorsSome unary operators can be used as both prefix and
postfix operators:
Example: increment (++) and decrement operators (--)
int a= b = 0;
++a; // a = 1
b = ++a; // b = 2, a=2
cout
-
8/9/2019 13 Operator Overloading
10/34
Computer Programming II #
C++OperatorsC++OperatorsSome operators can be used as both unary and binary
operators:
Example: the operator* can be used as a unary
operator for dereferencing and as a binary operator formultiplication.
int a, b, c;
a = b * c;
int a = 7;
int *b;
b = &a;cout
-
8/9/2019 13 Operator Overloading
11/34
Computer Programming II #
Overloadable C++OperatorsOverloadable C++Operators
Most of the operators in C++ can be overloaded:
+ - * / %
^& | ! = += -= *= /=
~= %= ^= &= |=
>>= * () []
new delete new[] delete[]
-
8/9/2019 13 Operator Overloading
12/34
-
8/9/2019 13 Operator Overloading
13/34
Computer Programming II #
Overloadable C++OperatorsOverloadable C++Operators
Restrictions: New operators cannot be created
Existing operators cannot be combined in a manner in which
they were not previously defined.
Existing details cannot be altered:
Precedence (the order in which they are evaluated)EX: a + b * c1st: b * c. 2nd: a + result of (b * c)
-
8/9/2019 13 Operator Overloading
14/34
Computer Programming II #
Overloadable C++OperatorsOverloadable C++Operators
Cannot create a new argument syntax for an operator:Ex: +a
Example: You cannot create a unary definition for an operator
that was previously only a binary operator (and vice versa)
Cannot redefine (override) an existing definition for an operator.
Example: You cannot change the definition for the +
operator with two integer arguments to do something other than add the
two together and return the result. Ex: a + b ( to mean multiplication)
-
8/9/2019 13 Operator Overloading
15/34
Computer Programming II #
Theory ofOperatorOverloadingTheory ofOperatorOverloading
Operator overloading does not provide anything entirely new,
but rather provides a different way of doing something:
Example: consider + and =
a.set (b.add (c));
a = b.add (c);
a = b + c;
Complex!!!!
Simple & Easy to understand
Both assigns sum of b and c to a
-
8/9/2019 13 Operator Overloading
16/34
Computer Programming II #
Theory ofOperatorOverloadingTheory ofOperatorOverloading
When overloading an operator, you should provide a definition thatthe user will expect:
Example: nobody expects the + operator to result in output being
printed to the screen!!!
Sometimes the definition might be different from what we are used
to, but it should make sense for whatever your class represents
Example: Using the + operator to concatenate two strings mightseem a little different for someone whos only used to
using it with numbers, but it follows the general concept
of addition
-
8/9/2019 13 Operator Overloading
17/34
Computer Programming II #
OperatorOverloading SyntaxOperatorOverloading Syntax
Write a function with the keyword operatorX,
where X is an operator symbol.
Example: operator+ ( arguments )
How to Overload operator??
-
8/9/2019 13 Operator Overloading
18/34
Computer Programming II #
OperatorOverloading SyntaxOperatorOverloading Syntax
Number of parameters in the declaration depend :
If the overloaded operator is unary orbinary
If the overloaded operator is being declared globally
or as a class method.
-
8/9/2019 13 Operator Overloading
19/34
Computer Programming II #
OperatorOverloading SyntaxOperatorOverloading Syntax
Unary Binary
operator@(x)
@ is declared globally
takes one parameter: x
x.operator@()
@ is a class methodx is the object (first arg)
operator@(x, y)
@ is declared globallytakes two parameter: x & y
x.operator@(y)
@ is a class methodx is the first arg & y is the second arg
-
8/9/2019 13 Operator Overloading
20/34
Computer Programming II #
OperatorOverloading Syntax / Example: Binary Operator (+)OperatorOverloading Syntax / Example: Binary Operator (+)class Distance
{
private:
int feet;
float inches;
public:
Distance() : feet(0),inches(0.0) {}
Distance(int ft, float in):
feet(ft),inches(in) {}
void getdist() {coutfeet;
coutinches;}
void showdist() {
cout
-
8/9/2019 13 Operator Overloading
21/34
Computer Programming II #
OperatorOverloading Syntax / Example: Binary Operator (OperatorOverloading Syntax / Example: Binary Operator (concatconcat))
class String {
private:
enum {SZ=80};
char str[SZ];
public:
String() { strcpy(str, );}
String(char s[])
{ strcpy(str, s); }
void display() const
{ cout
-
8/9/2019 13 Operator Overloading
22/34
Computer Programming II #
OperatorOverloading SyntaxOperatorOverloading Syntax
Output
Merry Christmas Happy New Year
Merry Christmas Happy New Year
s1, s2 and s3 (empty)
s3 after concatenation
-
8/9/2019 13 Operator Overloading
23/34
Computer Programming II #
23
-
8/9/2019 13 Operator Overloading
24/34
Computer Programming II #
-
8/9/2019 13 Operator Overloading
25/34
Computer Programming II #
Will you be myWill you be my friend?friend?
Friend-ship allows a class to selectively grant access to itsprivate internals to other constructs.
C++ friends come in three flavors:
friend functions (including overloaded operators)
friend classes friend methods (member functions)
Friend-ship is granted, not taken
A friend function can access both the private and protectedmembers of the class.
-
8/9/2019 13 Operator Overloading
26/34
Computer Programming II #
Will you be myWill you be my friend?friend?
To declare a function as a friend to a class, you must place
the function declaration inside of the class declaration and
prefix it with the keyword friend
class Rational {
friend Rational operator* (const Rational&,const Rational&);
Overloaded operator* is a friend to classR
ational.
-
8/9/2019 13 Operator Overloading
27/34
Computer Programming II #
#include
class Rational {
friend Rational operator* (Rational&, Rational&);
public:
Rational (int=0,int=1);
Rational operator=(const Rational&);
void print() { cout
-
8/9/2019 13 Operator Overloading
28/34
-
8/9/2019 13 Operator Overloading
29/34
Computer Programming II #
The Increment Operator (++)The Increment Operator (++)
A unary operator that can be used as both a prefix ( ++X)
and postfix (x++) operator.
First of all, when the compiler encounters the increment
operator in a statement, it will generate one of two calls: depends if the operator is prefix orpostfix
-
8/9/2019 13 Operator Overloading
30/34
Computer Programming II #
The Increment Operator (++)The Increment Operator (++)
Assume that we have overloaded both versions of the increment operatorfor a class Counter
If the compiler encounters a prefix call to the operator (of the form ++x) it
will generate a call toCounter::operator++()
Conversely, if the compiler encounters a postfix call to the operator (of theform x++) it will generate a call to
Counter::operator++(int)
dummy parameter to ensure
both versions have different
argument lists
When the compiler encounters a postfix increment operator, it simply
inserts a constant into the argument list to ensure that the second version
is called.
-
8/9/2019 13 Operator Overloading
31/34
Computer Programming II #
The Increment Operator (++)The Increment Operator (++)#include
using namespace std;
class Counter
{
private:
int count;
public:
Counter(): count(0) { }
Counter (int c): count (c) { }int get_count() const
{
return count;}
Counter operator++ () // prefix
{
return Counter (++count);}
Counter operator++ (int) //postfix
{
return Counter (count++);}
};
int main()
{Counter c1, c2; //c1=c2=0;
cout
-
8/9/2019 13 Operator Overloading
32/34
Computer Programming II #
Automatic Type Conversion (objects)Automatic Type Conversion (objects)
Two methods to define an automatic conversion:
Method 1
Declare and define a constructorthat takes a single argument of the
specified type.
Method 2
Declare and define a special type ofoverloaded operator
int x;
float y = 2.3;
x = y;
cout
-
8/9/2019 13 Operator Overloading
33/34
Computer Programming II #
Automatic Type ConversionAutomatic Type Conversion
Method 1: Declare and define a constructor that takes a single argumentof the specified type.
When the compiler sees f( ) called with
a One object, it looks at the
declaration forf( ) and notices it wants
a Two. Then it looks to see if theresany way to get a Two from a One, and
it finds the constructor
Two::Two(One), which it quietly calls.
The resulting Two object is handed to
f( ).
-
8/9/2019 13 Operator Overloading
34/34
Computer Programming II #
Method 2 Declare and define a special type ofoverloaded operator
Automatic Type ConversionAutomatic Type Conversion
The second way to effect automatic
type conversion is through operator
overloading. You can create a member
function that takes the current type andconverts it to the desired type using
the operatorkeyword followed by the
type you want to convert to. This form
of operator overloading is unique
because you dont appear to specify a
return type the return type is thename of the operator youre
overloading.