Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Object Oriented Programming Lab

Lab Manual (Lab 13)

School of Systems and Technology


UMT Lahore Pakistan
Objective:
The objective of this lab is to cover:

o Friend Functions
o Friend Classes
o Operator Overloading

Friend Function
A C++ friend functions are special functions which can access the private members of a class. A
friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.

#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob) Define friend Function
{
return float(ob.val1+ob.val2)/2; Friend function cannot access members of the class directly
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:

Enter two values: 10, 20


Mean Value is: 15

C++ friend Function and friend Classes


In this lab, we will learn to create friend functions and friend classes in C++ with the help of
examples.
Data hiding is a fundamental concept of object-oriented programming. It restricts the access of
private members from outside of the class.
Similarly, protected members can only be accessed by derived classes and are inaccessible
from outside. For example,

friend Function in C++


A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class.
Syntax:

class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}

Sample Code:

// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
private:
int meter;

// friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d) {

//accessing private members from the friend function


d.meter += 5;
return d.meter;
}

int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}

Friend Function to more than one classes / A Function Friendly to two


classes:
The following program demonstrates how friend functions work as a bridge between the
classes.

#include<iostream>
using namespace std;

class ABC;// forward declaration

class XYZ
{
int x;
public:
void set_data(int a)
{
x=a;
}

friend void max(XYZ,ABC);


};
class ABC
{
int y;
public:
void set_data(int a)
{
y=a;
}

friend void max(XYZ,ABC);


};

void max(XYZ t1,ABC t2)


{
if(t1.x>t2.y)
cout<<t1.x;
else
cout<<t2.y;
}

main()
{
ABC _abc;
XYZ _xyz;
_xyz.set_data(20);
_abc.set_data(35);

max(_xyz,_abc); //calling friend function


return 0;
}

Output
35

Friend Class
A friend class can access private and protected members of other class in which it is declared as
friend. It is sometimes useful to allow a particular class to access private members of other
class.
A friend class can access both private and protected members of the class in which it has been
declared as friend.
#include<iostream>
using namespace std;

class A
{
int x;
public:

A()
{
x=10;
}
friend class B; //friend class
};

class B
{
public:
void display(A &t) Write (A) because we use class A members in class B
{
cout<<endl<<"The value of x="<<t.x;
}
};

main()
{
A _a;
B _b;
_b.display(_a);
return 0;
}

Output

The value of x=10

In this example, class B is declared as a friend inside the class A. Therefore, B is a friend of class
A.
Class B can access the private members of class A.

Program to demonstrate friend Class

#include <iostream>
class A {
private:
int a;

public:
A() { a = 0; }
friend class B; // Friend Class
};

class B {
private:
int b;

public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
};

int main()
{
A a;
B b;
b.showA(a);
return 0;
}

Output
A::a=0
Program to demonstrate friend function of another class

#include <iostream>

class B; forward declaration

class A {
public:
void showB(B&); takes a reference to an object of class B as its parameter
};

class B {
private:
int b;

public:
B() { b = 0; }
friend void A::showB(B& x); // Friend function Declare Friend Function
};

void A::showB(B& x) Define Friend Function


{
// Since showB() is friend of B, it can
// access private members of B
std::cout << "B::b = " << x.b;
}

int main()
{
A a;
B x;
a.showB(x);
return 0;
}

Output
B::b = 0
Program to demonstrate global friend

#include <iostream>

class A {
int a;

public:
A() { a = 0; }

// global friend function


friend void showA(A&);
};

void showA(A& x)
{
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}

int main()
{
A a;
showA(a);
return 0;
}

Output
A::a=0

Following are some important points about friend functions and classes:
 Friends should be used only for limited purpose.
 Too many functions or external classes are declared as friends of a class with protected
or private data, it lessens the value of encapsulation of separate classes in object-
oriented programming.
 Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
 Friendship is not inherited
Merits:

 A friend function is able to access members without the need of inheriting the class.
 Friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operator.
 It can be declared either in the public or private or protected part of class.

Demerits:

 Friend functions have access to private members of a class from outside the class which
violates the law of the data hiding.
 Friend functions cannot do any run time polymorphism in its members.

Operator Overloading:
Similar to function overloading we can overload the operators. In this lab, we will learn about
operator overloading with the help of examples.
In C++, we can change the way operators work for user-defined types like objects and
structures. This is known as operator overloading. For example,
Suppose we have created three objects c1, c2 and result from a class named Complex that
represents complex numbers.
Since operator overloading allows us to change how operators work, we can redefine how
the + operator works and use it to add the complex numbers of c1 and c2 by writing the
following code:

Syntax for C++ Operator Overloading


To overload an operator, we use a special operator function. We define the function inside the
class or structure whose objects/variables we want the overloaded operator to work with.
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};

 returnType is the return type of the function.


 operator is a keyword.
 symbol is the operator we want to overload. Like: +, <, -, ++, etc.
 arguments is the arguments passed to the function.

Sample Code 1:
#include <iostream>
using namespace std;
class A
{

int x;
public:
A()
{}
A(int i)
{
x=i;
}
void operator+(A a)
{
cout<<"Value of x="<<x<<endl; 5
int m = x+a.x; cout<<"Value of a.x="<<a.x<<endl; 4
cout<<"The result of the addition of two objects is : "<<m;

}
void display();
};

int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output:

Sample Code 2:
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imaginary;
public:
Complex()
{
real=0;
imaginary=0;
}
Complex(int r,int i)
{
real=r;
imaginary=i;
}

void print()
{
cout<<real<<"+"<<imaginary<<"i"<<endl;
}

Complex operator + (Complex c)


{

Complex temp;
temp.real=real+c.real;
temp.imaginary=imaginary+c.imaginary;
return temp;
}
};

int main()
{
Complex c1(100,200);
Complex c2(100,200);
Complex c3;
c3= c1+c2;
c3.print();
}

Output:

Operator Overloading (cont.)


You can redefine or overload most of the built-in operators available in C++. Thus, a programmer
can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by
the symbol for the operator being defined. Like any other function, an overloaded operator has
a return type and a parameter list.
Sample Code:

#include <iostream>
using namespace std;
class Box {
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}

// Overload + operator to add two Box objects.


Box operator+( Box b) {
Box box;
box.length = length + b.length;
box.breadth = breadth + b.breadth;
box.height = height + b.height;
return box;
}
};

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}

Overloadable/Non-overloadable Operators
Following is the list of operators which can be overloaded −

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()
-> ->* new new [] delete delete []

Following is the list of operators, which cannot be overloaded −

:: .* . ?:

You might also like