Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 32

Introduction to Programming

Lecture 33
In Today’s Lecture
 Operator overloading
 Assignment operator
 A “this” pointer
 Operator over loading using this pointer
 Conversion function
Assignment
Operator
a=b;
Member Wise
Assignment
Member Wise Copy
Example
class String
{
char buf [ 100 ] ;
public:
String ( ) ;
~ String ( ) ;
...
};
Example
main ( )
{
String s1 ( “This is a test” ) ;
String s2 ;
s2 = s1 ;


}
s2 = s1 ;
Example
void String :: operator = ( String & s1 )
{
delete buf ;
buf = new char [ s1.buf + 1 ] ;
strcpy ( buf , s1.buf ) ;
}
Assignment Operator
int i , j , k ;
i=5;
j = 10 ;
k = 15 ;
i=j;
k=i;
i=j=k;
k=i=j;
k = i = ++ j ;
this pointer
this pointer
buf ;
this -> buf ;
( * this ).buf ;
int i ;
i = i ; // nothing happens
String s [ 1000 ] = { “This is a Test” } ;
s=s;
Self
Assignment
Example
main ( )
{
String s , * sPtr ;
sPtr = & s ;
.
.
.
s = * sPtr ;
}
Example
void String :: operator= ( String & other )
{
if ( this == & other )
return ;
--------
}
Example
String & String :: operator = ( String & other )
{
if ( this == & other )
return * this ;
delete buf ;
buf = new char [ other.length + 1 ] ;
strcpy ( buf , other.buf ) ;
return * this ;
}
s3 = s2 = s1 ;
cout << a << b << c ;
Example
Date d1 , d2 ;
d2 = d1 ++ ;
d2 = d1 + 1 ;
Example
Date date1 , date2 ;
date2 = date1 + 1 ;
date2 = date1 ++ ;
Example
main ( )
{
int i ;
float x ;
x=i;
i=x;
}
Example
main ( )
{
Date d ;

?
int i ;
d=i;
}
Example
main ( )
{
int i ;
float x ;
x = ( float ) i ;
}
Conversion
Function
Date ( )
{
// body of function
}
double x = 1 / 3 ; Output: 0.33333
x*3; Output: 0.99999
Common Business
Oriented Language

You might also like