0% found this document useful (0 votes)
14 views5 pages

Blg252e - Mod05 - 6spp Operator Overloading

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)
14 views5 pages

Blg252e - Mod05 - 6spp Operator Overloading

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/ 5

Operator

Operator Overloading
Overloading
►It is possible to overload the built-in C++ operators such
as +, >=, and ++ so that they invoke different functions,
depending on their operands.

Operator Overloading 5
►a+b will call one function if a and b are integers, but will
Operator Overloading call a different function if a and b are objects of a class.
►Operator overloading makes your program easier to write
and to understand.
►Overloading does not actually add any capabilities to C++.
Everything you can do with an overloaded operator you
can also do with a function.
►However, overloaded operators make your programs
easier to write, read, and maintain.

197 Object Oriented Programming 198

Operator
Operator Overloading
Overloading Limitations
Limitations
►Operator overloading is only another way of calling a ►You can’t overload operators that don’t already exist in
function. C++. You can overload only the built-in operators.
►You have no reason to overload an operator except if it ►You can not overload the following operators
Operator Overloading 5

Operator Overloading 5

will make the code involving your class easier to write and .
especially easier to read. *
►Remember that code is read much more than it is written ->
,
::
?:
sizeof

Object Oriented Programming 199 Object Oriented Programming 200

Limitations
Limitations Overloading
Overloading the
the ++ operator
operator for
for ComplexT
ComplexT
/* A class to define complex numbers */
►The C++ operators can be divided roughly into binary and class TComplex {
unary. Binary operators take two arguments. Examples are float real,img;
public:
a+b, a-b, a/b, and so on. Unary operators take only one
Operator Overloading 5

Operator Overloading 5

: // Member functions
argument: -a, ++a, a--. TComplex operator+(TComplex&); // header of operator+
function
►If a built-in operator is binary, then all overloads of it };
remain binary. It is also true for unary operators. /* The Body of the function for operator + */
TComplex TComplex::operator+(TComplex& z) {
►Operator precedence and syntax (number of arguments) TComplex result;
cannot be changed through overloading. result.real = real + z.real; int main() {
result.img = img + z.img;
►All the operators used in expressions that contain only return result; TComplex z1,z2,z3;
built-in data types cannot be changed. At least one } : // Other operations
z3=z1+z2; like z3 = z1.operator+(z2);
operand must be of a user defined type (class). }
Object Oriented Programming 201 Object Oriented Programming 202
Overloading
Overloading the
the Assignment
Assignment Operator
Operator (=)
(=) Overloading
Overloading the
the Assignment
Assignment Operator
Operator (=)
(=)
►Because assigning an object to another object of the same void ComplexT::operator=(const ComplexT& z)
type is an activity most people expect to be possible, the {
compiler will automatically create a type::operator=(const
Operator Overloading 5

Operator Overloading 5
re = z.re;
type &) if you don’t make one.
im = z.im;
►The behavior of this operator is member wise assignment.
It assigns (copies) each member of an object to members }
of another object. (Shallow Copy)
►You don't need to write such an assignment operator
►If this operation is sufficient you don't need to overload
function, because the operator provided by the compiler
the assignment operator. For example, overloading of
does the same thing.
assignment operator for complex numbers is not
necessary.

Object Oriented Programming 203 Object Oriented Programming 204

Overloading
Overloading the
the Assignment
Assignment Operator
Operator (=)
(=) Example
Example
class string {
►In general, you don’t want to let the compiler do this for int size;
you. char *contents;
Operator Overloading 5

Operator Overloading 5

►With classes of any sophistication (especially if they public:


void operator=(const string &); // assignment operator
contain pointers!) you want to explicitly create an
: // Other methods
operator=. };
void string::operator=(const string &s)
{
size = s.size;
delete []contents;
contents = new char[size+1];
strcpy(contents, s.contents);
}
Object Oriented Programming 205 Object Oriented Programming 206

Operator
Operator Provided
Provided by
by the
the Compiler
Compiler Operator
Operator of
of the
the Programmer
Programmer

Source object Destination object Source object Destination object


size 8 3
8 size size 8 3
8 size
Operator Overloading 5

Operator Overloading 5

0x008d0080 0x008d0080
0x00185d12 0x008d0080 0x00185d12
0x00ef0080
contents contents
contents: contents X

X
s a s s a
t b t t b
r c r r c
i \0 i i \0
n n n
g Data is still wasting g g
memory space.
1 1 1
\0 \0 \0

Object Oriented Programming 207 Object Oriented Programming 208


Return
Return value
value of
of the
the assignment
assignment operator
operator Copy
Copy Constructor vs. Assignment
Constructor vs. Assignment Operator
Operator
►When there’s a void return value, you can’t chain the ►The difference between the assignment operator and the
assignment operator (as in a = b = c ). copy constructor is that the copy constructor actually
►To fix this, the assignment operator must return a reference creates a new object before copying data from another
Operator Overloading 5

Operator Overloading 5
to the object that called the operator function (its address). object into it, whereas the assignment operator copies data
// Assignment operator , can be chained as in a = b = c into an already existing object.
const String& String::operator=(const String &in_object) {
if (size != in_object.size){ // if the sizes of the source and destination
size = in_object.size; // objects are different
delete [] contents; // The old contents is deleted
contents = new char[size+1]; // Memory allocation for the new contents
}
strcpy(contents, in_object.contents);
return *this; // returns a reference to the object
}
Object Oriented Programming 209 Object Oriented Programming 210

Copy
Copy Constructor vs. Assignment
Constructor vs. Assignment Operator
Operator Overloading
Overloading Unary
Unary Operators
Operators
► Unary operators operate on a single operand. Examples are the
►A a; increment (++) and decrement (--) operators; the unary minus, as in -5;
and the logical not (!) operator.
►A b(a);
Operator Overloading 5

Operator Overloading 5

► Unary operators take no arguments, they operate on the object for


►b=a; which they were called. Normally, this operator appears on the left
side of the object, as in !obj, -obj, and ++obj.
►A c=a; Example: We define ++ operator for class ComplexT to increment the
real part of the complex number by 0.1 .
int main() {
ComplexT z(1.2, 0.5);
++z; // operator++ function is called
z.print();
void ComplexT::operator++() {
return 0;
re=re+0.1;
} }
Object Oriented Programming 211 Object Oriented Programming 212

►To be able to assign the incremented value to a new object,


Overloading
Overloading the
the “[]”
“[]” Operator
Operator
the operator function must return a reference to the object. ►Same rules apply to all operators. So we don’t need to
// ++ operator discuss each operator. However, we will examine some
// increments the real part of a complex number by 0.1 interesting operators.
Operator Overloading 5

Operator Overloading 5

const ComplexT & ComplexT::operator++() {


re=re+0.1; ►One of the interesting operators is the subscript operator.
return *this; ►It can be declared in two different ways:
}
int main() { class C {
ComplexT z1(1.2, 0.5), z2;
z2 = ++z1; //++ operator is called, incremented value is assigned to z2 returntype & operator [] (paramtype);
z2.print(); or
return 0;
} const returntype & operator [] (paramtype) const;
};
Object Oriented Programming 213 Object Oriented Programming 214
►Example: Overloading of the subscript operator for the String
Overloading
Overloading the
the “[]”
“[]” Operator
Operator class. The operator will be used to access the ith character of the
►The first declaration can be used when the overloaded string. If i is less the zero then the first character and if i is greater
than the size of the string the last character will be accessed.
subscript operator modifies the object. The second
// Subscript operator
declaration is used with a const object; in this case, the char & String::operator[](int i) {
Operator Overloading 5

Operator Overloading 5
overloaded subscript operator can access but not modify the if(i < 0)
return contents[0]; // return first character
object. if(i >= size)
return contents[size-1]; // return last character
If c is an object of class C, the expression return contents[i]; // return i th character
}
c[i] int main() {
is interpreted as String s1("String 1");
s1[1] = 'p'; // modifies an element of the contents
c.operator[ ](i) s1.print();
cout << " 5 th character of the string s1 is: " << s1[5] << endl;
return 0;
}
Object Oriented Programming 215 Object Oriented Programming 216

Overloading Example: The function call operator is overloaded to copy a


Overloading the
the “()”
“()” Operator
Operator part of the contents of a string into a given memory location.
The function call operator is unique in that it allows any number of In this example the function call operator takes two arguments:
arguments. the address of the destination memory and the numbers of
class C{
returntype operator ( ) (paramtypes); characters to copy.
Operator Overloading 5

Operator Overloading 5

}; // The function call operator with two arguments


If c is an object of class C, the expression void String::operator( )( char * dest, int num) const {
if (num > size) num=size; // if num is greater the size of the string
c(i, j, k) is interpreted as for (int k=0; k < num; k++) dest[k]=contents[k];
}
c.operator( )( i, j, k )
int main( ) {
Example: The function call operator is overloaded to print complex String s1("Example Program");
numbers on the screen. In this example the function call operator does char * c = new char[8]; // Destination memory
s1(c,7); // First 7 letters of string1 are copied into c
not take any arguments. c[7] = '\0'; // End of string (null) character
// The function call operator without any argument, it prints a complex number cout << c;
void ComplexT::operator( )( ) const { delete [] c;
cout << re << " , " << im << endl ; return 0;
} }
Object Oriented Programming 217 Object Oriented Programming 218

"Pre"
"Pre" and
and "post"
"post" form
form of
of operators
operators ++
++ and
and --
-- Post-Increment
Post-Increment Operator
Operator
►Recall that ++ and -- operators come in “pre” and “post”
// postincrement operator
form.
►If these operators are used with an assignment statement ComplexT ComplexT::operator++(int) {
ComplexT temp;
Operator Overloading 5

Operator Overloading 5

than different forms has different meanings.


z2= ++ z1; // preincrement temp = *this; // old value (original objects)
z2 = z1++; // postincrement re= re + 0.1; // increment the real part
return temp; // return old value
►The declaration, operator ++ ( ) with no parameters
}
overloads the preincrement operator.
►The declaration, operator ++ (int) with a single int
parameter overloads the postincrement operator. Here, the
int parameter serves to distinguish the postincrement form
from the preincrement form. This parameter is not used.
Object Oriented Programming 219 Object Oriented Programming 220
Pre-Increment
Pre-Increment Operator
Operator
// postincrement operator
ComplexT ComplexT::operator++() {
Operator Overloading 5

re= re + 0.1; // increment the real part


return *this; // return old value
}

Object Oriented Programming 221

You might also like