0% found this document useful (0 votes)
264 views

Friend Function and Operator Overloading

The document discusses friend functions and operator overloading in C++. It provides examples of overloading common operators like +, -, <, ==, etc. as member functions and non-member functions. It also discusses restrictions on operator overloading like not changing precedence or arity of operators. The key points are: 1. Friend functions can access private members of a class. They are declared inside the class with the keyword 'friend'. 2. Operators can be overloaded to work on user-defined types by defining operator functions. 3. Common examples provided are overloading + to add two complex numbers, overloading unary - to reverse the sign of a class object, overloading < to compare

Uploaded by

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

Friend Function and Operator Overloading

The document discusses friend functions and operator overloading in C++. It provides examples of overloading common operators like +, -, <, ==, etc. as member functions and non-member functions. It also discusses restrictions on operator overloading like not changing precedence or arity of operators. The key points are: 1. Friend functions can access private members of a class. They are declared inside the class with the keyword 'friend'. 2. Operators can be overloaded to work on user-defined types by defining operator functions. 3. Common examples provided are overloading + to add two complex numbers, overloading unary - to reverse the sign of a class object, overloading < to compare

Uploaded by

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

Friend function and

Operator Overloading

Friendly function
If a function is defined as a friend function then,
the private and protected data of class can be
accessed from that function.
The complier knows a given function is a friend
function by its keywordfriend.
The declaration of friend function should be made
inside the body of class starting with keyword
friend.

Member function of one class can be


friend functions of another class.

Also declare all the member


functions of one class as the friend
functions of another class.

Operator Overloading
Redefine the meaning of operator when they
operate on class objects is known as operator
overloading.
This is done by operator function.

op is the operator being overloaded.


operator is the keyword.
operator op is the function name.

What does it mean?


Giving some special meaning to the operators to enable them
to operate on user defined data types.
Operator overloaded retains its original meaning.
(say if * is overloaded to multiply two class objects and can
always be used multiply two numbers)

Example
int nX = 2, nY = 3;
cout << nX + nY << endl;
C++ already knows how the plus operator
(+) should be applied to integer operands
the compiler adds nX and nY together and
returns the result.

What would happen in this case?

Mystring cString1 = "Hello, ";


Mystring cString2 = "World!";
cout << cString1 + cString2 <<
endl;

The intuitive expected result is that the string


Hello, World! is printed on the screen.
However, because Mystring is a user-defined class,
C++ does not know what operator + should do.
We need to tell it how the + operator should work
with two objects of type Mystring.
Once an operator has been overloaded, C++ will
call the appropriate overloaded version of the
operator based on parameter type.
If you add two integers, the integer version of
operator plus will be called.
If you add two Mystrings, the Mystring version of
operator plus will be called.

Examples of already overloaded operators


Operator << is both the stream-insertion operator and
the bitwise left-shift operator
+ and -, perform arithmetic on multiple types
Overloading an operator
Write function definition as normal
Function name is keyword operator followed by the
symbol for the operator being overloaded
Example : operator+ used to overload the addition
operator (+)

Restrictions on Operator Overloading

C++ operators that can be


Operators
that can be overloaded
overloaded
+

&

<

>

+=

-=

*=

/=

%=

^=

&=

|=

<<

>>

>>=

<<=

==

!=

<=

>=

&&

||

++

--

->*

->

[]

()

new

delete

new[]

delete[]

Operators
C++that
Operators
that cannot be
cannot be overloaded
. overloaded
.*
::
?:
sizeof

Restrictions on Operator Overloading


First, at least one of the operands in any overloaded
operator must be a user-defined type. This means you can
not overload the plus operator to work with one integer
and one double. However, you could overload the plus
operator to work with an integer and a Mystring.

No overloading operators for built-in types


Cannot change how two integers are added
Produces a syntax error

Restrictions on Operator
Overloading

Overloading restrictions

Precedence of an operator cannot be changed


Associativity of an operator cannot be changed
Arity (number of operands) cannot be changed
Unary operators remain unary, and binary operators
remain binary
Operators &, *, + and - each have unary and binary
versions
Unary and binary versions can be overloaded
separately

No new operators can be created


Use only existing operators
For example, you could not create an operator
** to do exponents.

The operator function can be defined


either as

1. Member function
OR

2. Friend function (non member


function)

Of the class which contains data


members to be operated by the
operator.

Defined as member function


1. Defined outside the class then
Return type operator op (arg_list);
(Declaration)
And
Return type class_name :: operator op
Objects of
Operator Specify
(arg_list)
this class
{is(definition)
to be
operated

symbol operands
+,_,*,/, other than
etc
one being
Function body.
used to
}
invoke this
op
2.Defined inside the class

Return_type operator op (arg_list)


{function body }

Defined as friend function


Declared and defined like any friend
function.
Number of operands to be passed as
arguments is same as number of
operands required for the operator.
That is for binary operation ,two
arguments are required and for
unary single argument is required.
( DIFFERENT FROM OPERATOR FUNCTION
DEFINED AS MEMBER FUNCTION)

OVEROADING ARITHMETIC
OPERATORS

1) Overloading unary operator (as member function)


void show()
{
class space
cout<<"x= "<<x<<" y= "<<y<<" z= "<<z;
{
}
int x;
void operator-()
int y; this pointer is a
{
int z; constant pointer that
x=-x;
holds the memory
y=-y;
public: address of the current
z=-z;
space() object.
}
{
};
x=y=z=0;
void main()
}
{
space(int x, int y, int z)
space s(3,-4,5);
{
s.show();
this->x=x;
-s;
// equivalent to s.operator-();
this->y=y;
//s2=-s will not work bcoz no val returned
this->z=z;
s.show();
}
}

2) Overloading unary operator


(as non-member function)
class space
{
int x;
int y;
int z;
public:
space()
{
x=y=z=0;
}
space(int x, int y, int z)
{
this->x=x;
this->y=y;
this->z=z;
}

void show()
{
cout<<"x= "<<x<<" y= "<<y<<" z= "<<z;
}
friend void operator-(space &s);
};
void operator-(space &s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
void main()
{
space s(3,-4,5);
s.show();
-s;
// equivalent to operator-(s);
// s2=-s will not work bcoz no val returned
s.show();
}

3) Overloading binary operator + (as


member function)
class complex
{
int real;
int imag;
public:
complex()
{}
complex(int r, int img)
{
real=r;
imag=img;
}
complex operator+(complex);
void show()
{
cout<<endl<<real<<"
+i"<<imag;
}
};

complex complex::operator+(complex c)
{
complex temp;
temp.real=real+c.real;
temp.imag=imag+c.imag;
return temp;
}
void main()
{
complex c1(3,4);
complex c2(5,6);
complex c3;
c1.show();
c2.show();
c3=c1+c2;
// equivalent to
c3=c1.operator+(c2)
c3.show();
}

C3=C1+C2;
As we know that a member function can be
invoked only by an object of the same class.
Here, the object C1 takes the responsibility of
invoking the function and C2 plays the role of
an argument that is passed to the function.
Its equivalent to C3=C1.operator+(C2);
The data members of C1 are accessed
directly and data members of C2 are
accessed using the dot operator.

Overloading Binary operators using


friends
Friend function requires two
arguments to be explicitly passed.

4) Overloading binary operator + (as nonmember function)


class complex
{
int real;
int imag;
public:
complex()
{}
complex(int r, int img)
{
real=r;
imag=img;
}
friend complex operator+
(complex,complex);
void show()
{
cout<<endl<<real<<" +j"<<imag;
}
};

complex operator+(complex c1,complex c2)


{
complex temp;
temp.real=c1.real+c2.real;
temp.imag=c2.imag+c2.imag;
return temp;
}
void main()
{
complex c1(3,4);
complex c2(5,6);
complex c3;
c1.show();
c2.show();
c3=c1+c2;
// equivalent to
c3=operator+(c1,c2);
c3.show();
}

Prefix increment Operator ++


Overloading
class Check
{ private: int i;
public:
Check(): i(0) { }
Check operator ++()
{ Check temp;
++i;
temp.i=i;
return temp;
}
void Display()
{ cout<<"i="<<i<<endl;
} };

int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();
obj1=++obj;
obj.Display();
obj1.Display();
return 0;
}

Postfix increment operator


overloading
Check operator ++
(int)
{ Check temp;
temp.i=i++;
return temp; }

int main()
{ Check obj, obj1;
obj.Display();
obj1.Display();
obj1=++obj;
obj.Display();
obj1.Display();
obj1=obj++;
obj.Display();
obj1.Display();
return 0; }

Output:i=0
i=0
i=1
i=1
i=2
i=1

Class exercise

Create a class called Distance with member


variables feet and inches. Give the required
constructor and getter and setter functions.
a) Overload the unary minus operator. store
the result in a distance object.
b)relational < operator to check whether dist1
is less than dist2.
c) binary + operator to add two distances
d) overload the assignment operator
e) overload the == operator.
f)prefix increment and postfix increment
operator.

Assignment Operator
overloading
Class sample
{
private:
int x, y;
public:
sample(int a,int b)
{
x=a;
y=b;
}

void operator = (sample


obj)
{
x= obj.x;
y= obj.y;
}
void display ()
{
cout<<\n value of x<<x;
cout<<\n value of y<<y;
}
};

Main(){
Sample obj1(10,20), obj2(3,4);
obj2=obj1;
obj2.display();
}

==operator [ As a non-member function]


int operator ==(sample &ob1, sample &ob2)
{ if(ob1.x == ob2.x && ob1.y == ob2.y)
return1;
else
return(0);
}
Example:
Sample obj1(23,24);
Sample obj2(12,34);
If (obj1==obj2)
{cout<< Equal;} else{cout <<Not equal;
}

==operator [As a Member


function
int operator ==(sample &ob2)
{ if(x == ob2.x && y == ob2.y)
return1;
else
return(0);
}

< operator [ As a non-member


function]
int operator < (sample &ob1, sample
&ob2)
{ if(ob1.x< ob2.x && ob1.y < ob2.y)
return(1);
else
return(0); }

Stream Extraction (<<) and


Insertion (>>)Operator
The standard C++ library includes the header file iostream, where the standard input and output stream objects are
declared.
the standard output of a program is the screen, and the C++ stream object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).
1 .cout << "Output sentence";
2 .cout << 120;
3. cout << x;
The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the
constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout.
Standard Input (cin).
The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the
overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store
the data that is going to be extracted from the stream. For example:
1 int age;
2 cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from cin (the
keyboard) in order to store it in this integer variable.

Overloading Stream-Insertion and


Stream-Extraction Operators
Overloaded << and >> operators
Overloaded to perform input/output for
user-defined types
Left operand of types ostream & and
istream &
Must be a non-member function
because left operand is not an object of
the class
Must be a friend function to access
private data members

Overloading stream extraction( << )and


insertion (>>) operator for userdefined data
type
Syntax
// ostream's insertion operator definition
ostream& operator<< (ostream& os, const
Class& obj);
// istream's extraction operator definition
istream& operator>>(istream &is, Class
&obj);

Example:class PhoneNumber
{
private:
string areaCode; // 3-digit area code
string exchange; // 3-digit exchange
string line; // 4-digit line
public:
friend ostream &operator<<( ostream &, const
PhoneNumber & );
friend istream &operator>>( istream &, PhoneNumber &
);
}; // end class PhoneNumber

ostream &operator<<( ostream &output, const


PhoneNumber &number )
{
output << "(" << number.areaCode << ") <<
number.exchange << "-" << number.line;
return output;
// enables cout << a << b << c;
}

istream &operator>>( istream &input,


PhoneNumber &number )
{
input >> setw( 3 ) >> number.areaCode; // input
area code
input >> setw( 3 ) >> number.exchange;
// input exchange
input >> setw( 4 ) >> number.line; // input line
return input;
}

int main()
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form :" << endl;
cin >> phone // invokes operator>> by implicitly issuing the global function call operator>>( cin,
phone )
cin >> phone;
cout << "The phone number entered was: ; // cout << phone invokes operator<< by implicitly
issuing
// the global function call operator<<( cout, phone )
cout << phone << endl;
return 0;
}

Output
Enter phone number in the form :
800 555 1212
The phone number entered was: (800) 555-1212

Class exercise
Overload the Input
Output operator for
the Complex Class:

ostream& operator<<(ostream &os, const complex& c)


{ os << c.real << '+' << c.imag << 'i' << endl;
return os;
}
complex c1(3,5);
cout<<c1;
Output:3+5 i

Subscript operator[]
const int SIZE = 10; overloading
class ArrayList
{ private:
int arr[SIZE];
public:
ArrayList() ;
int &operator[](int i)
{ if( i > SIZE )
{ cout << "Index out of bounds"
<<endl;
// return first element. return
arr[0];
}
return arr[i];
}
};

ArrayList::ArrayList()
{ register int i;
for(i = 0; i < SIZE; i++)
{ arr[i] = i; }
}
int main()
{ ArrayList A;
cout << "Value of A[2] : " << A[2]
<<endl;
cout << "Value of A[5] : " <<
A[5]<<endl;
cout << "Value of A[12] : " <<
A[12]<<endl; return 0;
}

Output:
Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0

function call () operator overloading

The function call


operator can take
any number of
arguments of any
types and return
anything it wishes
to.

class IntArray
{ private:
int *ptr;
public:
IntArray(int size) { ptr = new int[size]; }
~IntArray() { delete [] ptr; }
int& operator[](int index);
int& operator()(int index); };
//Function call operator
int& IntArray::operator()(int index){ return
ptr[index]; }

int main(void)
{ IntArray iArray(10);
iArray(0) = 5;
iArray(1) = 3;
cout << iArray(0)
<< endl;
cout << iArray(1)
<< endl; return
0; }

Output
5
3

New and delete operator


overloading
Why overload new and
delete?
To take charge or control
over how to allocate
memory
To aid in debugging; keep
track of memory allocation
and deallocation in the
program
To do some other operation
apart from allocating
memory at the time of
memory
allocation/decallocation

String Operator Overloading


class MyString
{
char *value;
int len;
public:
MyString()
{
len=0; value=0; }
~MyString(){ }
//String From Array
MyString(char *s)
{
len=strlen(s);
value=new char[len+1];
strcpy(value,s);
}
//String using Copy Constructor
MyString(MyString & s)
{
len=s.len;
value=new char[len+1];
strcpy(value,s.value);
}

friend MyString operator+(MyString obj1,MyString


obj2);
friend int operator==(MyString obj1,MyString obj2);
friend int operator!=(MyString obj1,MyString obj2);
friend int operator<(MyString obj1,MyString obj2);
friend int operator<=(MyString obj1,MyString obj2);
friend int operator>(MyString obj1,MyString obj2)
friend int operator>=(MyString obj1,MyString obj2);
void display()
{
if(len==0)
{
cout<<"\n String is Empty \n";
}
else
{
cout<<"\nThe result is:"<<value<<"\n";
}
}
};

MyString operator+(MyString obj1,MyString obj2)


{
MyString obj3;
obj3.len=obj1.len+obj2.len;
obj3.value=new char[obj3.len+1];
strcpy(obj3.value,obj1.value);
strcat(obj3.value,obj2.value);
return obj3;
}
Example:
Mystring str1(Hello);
MyString str2(World);
MyString str3;
Str3=str1+str2
- HelloWorld

==Operator
int operator==(MyString obj1,MyString
obj2)
{
int rel=0;
if(strcmp(obj1.value,obj2.value)==0){
rel=1;
}
return rel;
}

!=Operator
int operator!=(MyString obj1,MyString
obj2)
{
int rel=0;
if(strcmp(obj1.value,obj2.value)!=0)
{
rel=1;
}
return rel;
}

int operator<(MyString obj1,MyString


obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2.value);
if(rel<0) { result=1; }
return result;
}

>= Operator
int operator>=(MyString obj1,MyString obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2.value);
if(rel>0 || rel==0) { result=1; }
return result;
}

You might also like