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

Operator Overloading I

by jitendra singh chauhan(Project Engineer)CDAC Noida


Objectives of this
session
 Identify need of operator overloading
 State Rules/restrictions on operator overloading
 Overload arithmetic operators for class Complex
 Overload Pre & Post increment/Decrement operators
 Overload assignment operator
 Distinguish between overloaded assignment operator & copy
constructor

by jitendra singh chauhan(Project Engineer)CDAC Noida


Need of Operator
Overloading
 Operator Overloading is a feature of C++ because of which
additional meanings can be given to existing operators.
 Operator Overloading is an important technique that
enhances power of extensibility.
 operator is keyword in C++ which is used to implement
operator overloading.
 Operator Overloading feature makes ADT’s more natural &
closer to built in data types.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Restrictions on Operator
Overloading
 One cannot
 define new operators such as **
 change the precedence or associativity of an operator
 change arity of operators.
 Meaning of an operator when applied to built in data types.
 Overload following operators : . :: ?: sizeof

by jitendra singh chauhan(Project Engineer)CDAC Noida


Format
Format for
for operator
operator functions
functions

Return_type class_name :: operator #(argument list )


{
… … // operations
}
where,
# is a placeholder. Substitute operator for the #
E.g. Complex Complex :: operator + (Complex &)
operator functions are non static member functions
of a class.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘+’
‘+’ Operator
Operator for
for Class
Class Complex
Complex

// part of main
{
Complex c1(1, 3);
Complex c2 (3, 5);
Complex c3 = c1 + c2;
}
+ operator will work for Complex objects if operator +
is overloaded for class Complex.
statement 3 can be resolved as
c3 = c1.operator + (c2) // as a member function or
c3 = operator + (c1,c2) // as a friend function

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘+’
‘+’ Operator
Operator for
for Class
Class Complex
Complex

// Part of Complex.cpp file


Complex Complex :: operator + (const Complex & c)
// prototype for operator + overloading
{
Complex temp;
temp.m_real = this ->m_real + c.m_real;
temp m_imag = this ->m_imag + c.m_imag;
return(temp);
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘-’
‘-’ Operator
Operator for
for Class
Class Complex
Complex

// Part of Complex.cpp file


Complex Complex :: operator - (const Complex & c)
// prototype for operator - as a binary subtraction operator
{
Complex temp;
temp.m_real = this ->m_real - c.m_real;
temp m_imag = this ->m_imag - c.m_imag;
return(temp);
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘-’
‘-’ Operator
Operator for
for Class
Class Complex
Complex

// Part of Complex.cpp file


Complex Complex :: operator - ()
// prototype for operator - as a unary negation operator
{ void main (void)
Complex temp; {
temp.m_real = - m_real; Complex c1 (1,2), c2;
temp m_imag = - m_imag; c2 = -c1;
return(temp); }
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘++’
‘++’ Operator
Operator for
for Class
Class Complex
Complex

// part of main
{
Complex c1(1, 3);
Complex c2 ;
c2 = c1++;
c2 = ++c1; // c2 = c1.operator ++()
}
++ operator will work for Complex objects if
operator ++ is overloaded for class Complex.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘++’
‘++’ Operator
Operator for
for Class
Class Complex
Complex

++ as a PreIncrement Operator
Complex & Complex :: operator++( ) // Unary operator
// hidden parameter is this pointer
{
++m_real; //or m_real++;
++m_imag; // or m_imag++;
return(*this);
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘++’
‘++’ Operator
Operator for
for Class
Class Complex
Complex

++ as a PostIncrement Operator
Complex Complex :: operator++( int ) // Unary operator
// hidden parameter is this pointer
// int is a dummy parameter
{
Complex Temp = *this ;
m_real++ ;
m_imag++ ;
return(Temp);
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘‘ == ’’ Operator
Operator for
for Class
Class String
String

//part of client code


void main (void)
{
String s1(“SEED”) ;
String s2 (“ Infotech” ) ;
String s3;
s1 = s2 ; // does member wise copy that leads to
// dangling pointer & memory leakage
// problems
} // the call will be resolved as s1.operator=(s2);

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘‘ == ’’ Operator
Operator for
for Class
Class String
String

To avoid Dangling Pointers & Memory Leakage ,


Programmer has to overload assignment operator for
the classes which have pointer as a data member.
Steps involved :
1) Delete old buffer.
2) Allocate enough new memory.
3) Copy the string
4) Modify the code to return the object for cascade
use eg s1 = s2 = s3 in client code.
s1 = s1

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Overload ‘‘ == ’’ Operator
Operator for
for Class
Class String
String

// part of String.cpp file


String & String::operator=(const String &s)
{

if(this == &s)
return(*this); // step 4
{
else
m_len = s.m_len;
delete [ ] m_pbuff; // step 1
m_pbuff = new char [m_len + 1]; // step 2
strcpy(m_pbuff,s.m_pbuff); // step 3
return (*this); }
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overloaded
Overloaded ‘‘ == ’’ Operator
Operator && Copy
Copy Constructor
Constructor

Distinguish between the situation where copy


constructor will be called & where overloaded
assignment operator will be called.
// part of main
{
String s1( “XYZ”) ;
String s2 ;
s2 = s1;
String s3 = s1;
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Few
Few more
more can
can be
be ...
...

On the similar lines one can overload


Few more Unary Operators like say ! Pre & post --
Few more Binary Operators can be
Arithmetic - * /
Equality Relational == !=
Inequality Relational < > <= >=
Which operator should be overloaded for which class
depends upon possible use of the class in client code.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Operator Overloading II

by jitendra singh chauhan(Project Engineer)CDAC Noida


Objectives of this
Session
 Identify need of a friend function using example
 Overload + operator to add built in data type to
Complex object
 Overload insertion >> / extraction << operators for
Complex Class
 State Rules for friend functions
 Overload Operator subscript [ ] ,( ) for class String
 Identify need of conversion operators & how to use them.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Identify need of a
friend function
// part of main
{
Complex c1(1,2),c2;
c2 = c1 + 5 ; //c1.operator+ (int );
//overload operator+ for this signature
c2 = 5 + c1 ; // ? Since 5 is not an object
}
Note for c1 = c2 + c3
// option 1 : Complex operator+ (const Complex&)
using member fn where this is passed implicitly
// option 2 :
Complex operator+ (const Complex&,const Complex&)
using friend function

by jitendra singh chauhan(Project Engineer)CDAC Noida


friend
functions
 friend is a keyword.
 friend functions are not member functions of class. Therefore
they do not receive implicit this pointer.
 Friend function is declared in public or private part of class. It
has access right of private data members of the class of which
it is a friend.
 Definition of friend function is written like all normal
functions. (Ret_type Fn_Name (Arg List.) No need to use
scope resolution operator since not the member function of
the class.

by jitendra singh chauhan(Project Engineer)CDAC Noida


friend
functions
 Whenever first operand happens to be of built in type, then
use friend function to overload
 Eg int & object of Class Complex
 When you want to perform operations on two dissimilar data
types you need to use friend functions.
 One of the argument to a friend function should be of the class
of which it is a friend
 friend function should be used only when it is absolutely
necessary since it defeats object oriented paradigm.

by jitendra singh chauhan(Project Engineer)CDAC Noida


Add built in data type to
Complex object
// part of Complex.h file
class Complex {
private :
int m_real,m_imag;
public:
……
friend Complex operator+(int,const Complex&);
};
// declaration of friend function
// now operator+ fn with above signature is friend of class
Complex

by jitendra singh chauhan(Project Engineer)CDAC Noida


Add built in data type to
Complex object
// part of .cpp file
{
Complex operator+(int i,const Complex& c)
// note a) no need of friend keyword in function definition
// b) no need of scope resolution operator
Complex temp;
temp.m_real = i + c.m_real;
temp.m_imag = c.m_imag;
return(temp);
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload ‘ <<‘ for
Complex object
//declare ‘operator<<‘to be friend fn of Complex class
// part of .cpp file
{
ostream& operator<<(ostream & o,const Complex& c)
o<<“Real Part is : ”<<c.m_real; void main ( )
o<<“Imag Part is: ”<<c.m_iamg; {
return ( o); Complex c1,c2;
} cout<< c1;
//operator<<(cout, c1);
cout<<c1<<c2;
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


friend function should not
be used for
= Assignment operator
[] Subscripting operator
() Function call operator
-> Class member access operator

 All the above operators should be overloaded using a non-


static member function of the class
 friend function cannot be used to overload them

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload Operator
subscript [ ]
//part of main
{
String s1(“seed”);
char ch = s1[ 3] ; //ch = s1.operator[ ] (3);
s1[ 0 ] = ‘S’ ; // s1.operator [ ] (0) = ‘S’;
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload Operator
subscript [ ]
// part of .cpp for case 1
// ie ch = s1[ 3] //resolved as ch = s1.operator[ ] (3);
Prototype: char String:: operator [ ] (int );
char String : : operator [ ] (int i )
{
assert (i>=0 && i<m_len); //include assert.h
return(*(m_pbuff+i));
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload Operator
subscript [ ]
// part of .cpp for case 2
// ie s1[ 0] = ‘S’ ; //resolved as s1.operator[ ] (0) = ‘S’;
Prototype: char& String:: operator [ ] (int );

char& String : : operator [ ] (int i )


{ assert (i>=0 && i<m_len); //include assert.h
return(*(m_pbuff+i));}
// this is a right prototype for both case 1 & 2

by jitendra singh chauhan(Project Engineer)CDAC Noida


Overload
Operator ()
// Part of .cpp file // Part of main()
char String :: operator ()() { String s1 (“ABCDEFG”);
{ while ()
if (count < m_len) {
return (m_pbuff [ count++]);ch = s1();
else // called as fn. call operator
count = 0; // fn. objects
} }
}
Add count as a data member of class string and initialize
it to zero in constructor

by jitendra singh chauhan(Project Engineer)CDAC Noida


Type
Conversions
 Compiler cannot support automatic type conversion for UDT’s
 Possible Data Conversions between uncompatible types
 Conversion from built-in type to class type
 Conversion from class type to built-in type
 conversion from one class type to another class type

by jitendra singh chauhan(Project Engineer)CDAC Noida


Built-in type to
Class type
 Built-in type to class type conversion can be achieved using
constructor
eg. String :: String (Char *);
// Client code
String s1;
char * name 1 = “SEED”;
s1 = string (name1);
// converts from char * to String object
// as if name1 is type casted to object of your class

by jitendra singh chauhan(Project Engineer)CDAC Noida


Built-in type to
Class type
 Built-in type to class type conversion can be achieved using
constructor
eg. int x = 10;
Complex c1;
c1 = x; // type mismatch
c1 = Complex (x); // constructor syntax

 Constructors can be called explicitly using a keyword explicit

by jitendra singh chauhan(Project Engineer)CDAC Noida


Class Type to
Built-in type
 To do this C++ has feature referred as conversion function
 Syntax :
operator typename()
{
……
}
 This function converts class type data to typename
 eg. operator int() converts class type data to int

by jitendra singh chauhan(Project Engineer)CDAC Noida


Conversion
Functions
 Must be a class member

 Return type is not required explicitly

 There are no explicit arguments but implicit argument is there


which is this

by jitendra singh chauhan(Project Engineer)CDAC Noida


Conversion Function -
Example
 // part of fraction.h file
class Fraction
{
private:
long m_num;
long m_den;
public:
Fraction (long, long d = 1);
operator float ();
}

by jitendra singh chauhan(Project Engineer)CDAC Noida


Conversion Function -
Example
 // part of main()
{
Fraction f1(3, 7); // 3/7
float f;
f = f1;
//Compile time error if conversion function is not
defined
f = f1; // implicitly calls conversion
// function
f = f1.operator float(); // explicit call
f = (float) f1; // typecast syntax
}
by jitendra singh chauhan(Project Engineer)CDAC Noida
Conversion from one class
to another class

class A class B {
{ { A a1;
A (B&); operator A(); B b1;
} } a1 = b1;
}
Whether constructor or conversion function should be
used depends upon which class code is available for
programmer for modifications.
by jitendra singh chauhan(Project Engineer)CDAC Noida
Try this
 Construct a class to represent array of integers
 Write default value constructor, parameterized constructor for
the class say intArray
 Write destructor for the same
 overload subscript operator.
 Confirm that following operations are allowed
intArray arr1(10);
arr1[0] = 5;
arr1[1] = 7;

int x = arr1 [6];

by jitendra singh chauhan(Project Engineer)CDAC Noida

You might also like