0% found this document useful (0 votes)
50 views12 pages

Lab 6 Friend Classes and Friend Functions

OOP practice

Uploaded by

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

Lab 6 Friend Classes and Friend Functions

OOP practice

Uploaded by

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

School Of Electrical Engineering

Course Name
Object Oriented Programming

Subject Instructor Dr. SADIQ AMIN


Lab Instructor SYED ZAIN UL HASSAN

Group Members
Muhammad Taha (455060)
Muhammad Hassan (466391)

EXPERIMENT NO 4
Friend Classes and Friend Functions
Introduction
The following lab enables the student to get a good grip on the concept of friend functions and
classes which really do help in accessing the private information of another class. This really
provides a hack in accessing the private information outside of the class .

Objectives:
To understand the concept of making classes and functions friend to other classes for data
sharing Equipment required:

To understand the functionality of friend functions and classes and enhancing the
concept through real world modulations.

Visual Studio/Dev C++

Description:

Friendship helps in accessing the private data members of class. Thus it enables a class to
grant the access to any other class without inheriting that class. If two classes do not fulfill
“is-a” relationship and are required to access the private member function of any class it is
declared as friend class of that class. Friend functions are also meant for the same purpose.

Friend classes
All member functions of a class become friends of the friendship-granting class. Friendship
granting class allows the other class to access all the private, protected, public members
directly using (.) operator with Friendship-granting class object.
Friend Class Example
class alpha { int
data; public: alpha():
data(99){}
friend class beta; // granting
friendship
}; class beta { public: void
func1(alpha a) {cout<<a.data;}
void func2(alpha a)
{cout<<a.data;}
};

Friendship-grant is not commutative. It is not dual side relationship until or unless declared
in both the classes separately

LAB TASK

I. Write a program to find Maximum out of two numbers using friend function. Here
one member is of one class and second belongs to another class.

CODE
#include <iostream>
using namespace std;

OUTPUT SNIPPET class Class1 {


private:
int first_number;
II. Write a program to swap the values of
public:
private data Class1(int x) : first_number(x) {}
members of classes
names class_1 and friend class Class2; class_2 using friend
keyword };

CODE class Class2 {


private:
int second_number;

public:
Class2(int x) : second_number(x) {}

void output_func(Class1& obj) {


int output = 0;
if (second_number > obj.first_number) {
output = second_number;
cout << "The max number is: " <<
output << endl;
} else if (obj.first_number >
second_number) {
output = obj.first_number;
#include <iostream>
using namespace std;

class Class1 {
private:
int first_number;

public:
Class1(int x) : first_number(x) {}
friend class Class2;
};

class Class2 {
private:
int second_number;

public:
Class2(int x) : second_number(x) {}

// Function to swap numbers


void swap_func(Class1& obj) {
int temp = obj.first_number;
obj.first_number = second_number;
second_number = temp;
}

// Function to output numbers before swapping


void output1_func(Class1& obj) {
cout << "Numbers before swapping: " << endl;
cout << "First Number = " << obj.first_number << endl;
cout << "Second Number = " << second_number << endl << endl;
}

// Function to output numbers after swapping


void output2_func(Class1& obj) {
cout << "Numbers after swapping: " << endl;
cout << "First Number = " << obj.first_number << endl;
cout << "Second Number = " << second_number << endl;
}
};

int main() {
int var;
cout << "Enter the first number: ";
cin >> var;
Class1 object1(var);

cout << "Enter the second number: ";


cin >> var;
Class2 object2(var);

object2.output1_func(object1);
object2.swap_func(object1);
object2.output2_func(object1);

return 0;
}
}
OUTPUT SNIPPET

III. Create a class called Rectangle. It should contain a constructor for width and height,
a function that returns the area and a friend function that duplicate the rectangle's
dimensions. In the main, create a rectangle instance, duplicate it and print out the
area.

CODE
#include <iostream>
using namespace std;
class Rectangle
{
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}

double area() const


{
return width * height;
}
friend Rectangle duplicate(const Rectangle& rect);
};
Rectangle duplicate(const Rectangle& rect)
{
return Rectangle(rect.width * 2, rect.height * 2);
}
int main()
{
Rectangle rect(4.0, 5.0);
Rectangle duplicatedRect = duplicate(rect);
cout << "Area of the duplicated rectangle: " << duplicatedRect.area() << endl;
return 0;
} Rectangle(double x, double y) {
width = x;
height = y;
}

Rectangle() : width(0), height(0) {}


void area() const {
cout << "The area is: " << (width * height) << endl;
}
friend void Duplicate(Rectangle& R1, Rectangle& R2);
};

void Duplicate(Rectangle& R1, Rectangle& R2) {


R2.width = R1.width;
R2.height = R1.height;
cout << "The height of the duplicated rectangle is: " << R2.height << endl;
cout << "The width of the duplicated rectangle is: " << R2.width << endl;
}

int main() {
cout << "Enter height and width of the first rectangle: " << endl;
float x, y;
cin >> x >> y;

Rectangle R1(x, y);


Rectangle R2;

R1.area();

Duplicate(R1, R2);
R2.area();

return 0;
}
OUTPUT SNIPPET
IV. Create a class called Box with a variable: width of type double. Inside the class
define a constructor and a friend that prints the width value(printWidth). In the
main() define a Box instance, set values and call printWidth. Home Task:

CODE

#include <iostream>
using namespace std;
class Box
{
private:
double width;
public:
Box(double w) : width(w) {}

void setWidth(double x)
{
width = x;
}

double printWidth() const {


return width;
}

friend Box duplicate(const Box& box);


};

Box duplicate(const Box& box)


{
return Box(box.width);
}
int main()
{
Box box(4.0);
cout << "Width of the original box: " << box.printWidth() << endl;
OUTPUT

V. Create two classes DM and DB which stores the value in distances. DM stores
distance in meters and centimeters and DB in feet and inches. Write a program that
can read values for the class objects and add one object of DM with another object
of DB. Use a friend function to carry out the addition operation. The object that
stores the results may be a DM object or DB object, depending on the units in
which the results are required. The display should be in the format of feet and
inches or meters and centimeters depending on the object on display.

CODE
#include <iostream>
using namespace std;

class DM; // Forward declaration

class DM {
private:
int meters;
int centimeters;

public:
DM(int m, int cm) : meters(m), centimeters(cm) {}

friend DM addDistances(const DM& dm, const class DB& db);

void display() const {


cout << "Distance: " << meters << " meters and " << centimeters << " centimeters." << endl;
}
};

class DB {
private:
int feet;
int inches;

public:
DB(int ft, int in) : feet(ft), inches(in) {}

friend DM addDistances(const DM& dm, const DB& db);

void display() const {


cout << "Distance: " << feet << " feet and " << inches << " inches." << endl;
}
};

// Friend function to add DM and DB objects and return a DM object


DM addDistances(const DM& dm, const DB& db) {
int total_centimeters = dm.meters * 100 + dm.centimeters + db.feet * 30.48 + db.inches * 2.54;
return DM(total_centimeters / 100, total_centimeters % 100);
}

int main() {
int meters, centimeters, feet, inches;
cout << "Enter distance in meters and centimeters: ";
cin >> meters >> centimeters;
DM dm(meters, centimeters);

cout << "Enter distance in feet and inches: ";


cin >> feet >> inches;
DB db(feet, inches);

DM result = addDistances(dm, db);

cout << "\nResult in meters and centimeters:" << endl;


result.display();

return 0;
}
OUTPUT

THINK

i. Why friendship is needed?


Answer
Friendship is needed when an external function wants to access the private
members of an class we make that function the friend of that class . Let’s dive
deep down with an analogy. Our friends have access to our private things just
like this friend function can access private members of the class .
ii. Inheritance vs. friends, what do you prefer? Justify?
Answer
Inheritance and friends functions do not depend upon the user favorability
rather than the functionality of program. Everything truly depends upon the
conditions and scenarios we are given in the program for code .
I do think inheritance is better than friends as in inheritance we still have
command over encapsulation while in friends can access the private members
of the class .
iii. Why do we make friend functions? iv. Are friend functions parts of a class?
Answer
We make friend function for accessing the private members of the class .
Friends can access the private members of the class without giving any error
while those functions are not the part of the class created . Those functions
are not called by object as they are not member of the class .
iv.Does friendship effects the privacy of class?
Answer
I do think it affects the privacy of class but if we know the function than we
can access the private members of the class . But we are truly giving access
of the private members of the class to the outside of the class declared. The
act of hiding data is breached easily without any difficulty.

Conclusion
Friendship in C++ provides a way for external functions to access
private members of a class, similar to how close friends can share access
to personal aspects of our lives. While it is a useful feature for certain
scenarios, it does compromise data privacy since it bypasses
encapsulation. On the other hand, inheritance maintains encapsulation
while allowing code reuse and structure. The choice between using
inheritance or friend functions should be guided by the program's
requirements and desired functionality, as both have their unique
advantages and drawbacks.

You might also like