You are on page 1of 7

NAME: H.

M NABEED BUKSH
PROGRAM: (BEE)
SECTION: 3A
SUBJECT: OBJECT ORIENTED PROGRAMMING
SUBMITTED TO: PROF ATTAYAB
ASSIGNMENT NO. 2
QUESTION 1
What are friend functions and when are they used?
Friend function of a class is defined outside the class but it has right to access all private and
protected members of the class. A friend function is used to access all the non-public
members of a class. You can use a friend function to bridge two classes by operating
objects of two different classes

QUESTION 2
Write the syntax to define friend functions.
The syntax is
Return_type Function_name (ClassName Obj)
{
Obj.private_dataMember;
}

QUESTION 3
Write a class called Machine with data member (current_ cycle as int), and
member functions (start ( ), next ( )). We need to define constants such as idle=
0, gear1 =1, gear2 =2, gear3 =3, gear4 =4 and gear5 =5. The start function acts as
the starter of the machine where we set the initial current cycle value. The next
method changes the current_ cycle’s value using constants value. Write the
appropriate class and the main function to start the machine and change the
machine gears accordingly.
CODE:
#include<iostream>
using namespace std;
class machine
{
public:
int current_cycle;
const int idle=0, gear1=1, gear2=2, gear3=3, gear4=4, gear5=5;
public:
void start()
{
current_cycle = idle;
cout << "current_cycle value is:" << current_cycle << endl;
}
void next()
{
{
if (current_cycle == idle)
{
cout << "the Gear value : " << current_cycle << endl;
current_cycle++;

if (current_cycle == gear1)
{
cout << "the Gear value : " << current_cycle << endl;
current_cycle++;
if (current_cycle == gear2)
{
cout << "the Gear value : " << current_cycle << endl;
current_cycle++;
if (current_cycle == gear3)
{
cout << "the Gear value : " << current_cycle << endl;
current_cycle++;

if (current_cycle == gear4)
{
cout << "the Gear value : " << current_cycle << endl;
current_cycle++;
if (current_cycle == gear5)
{
cout << "the Gear value : " << current_cycle << endl;
}
else
{
cout << "Machine does not work properly" << endl;
}
}
else
{
cout << "Machine does not work properly" << endl;
}
}
else
{
cout << "Machine does not work properly" << endl;
}
}
else
{
cout << "Machine does not work properly" << endl;
}
}
else
{
cout << "Machine does not work properly" << endl;
}
}
else
{
cout << "Machine does not work properly" << endl;
}
}
}
};
int main()
{
machine m1;
m1.start();
OUTPUT:
m1.next();
}
QUESTION 4
Write a class that allows a non-member function access to the private members
of a class. (Hint: friend keyword)
#include<iostream>
using namespace std;
class Myclass
{
int a,b,c;
public:
void get_int()
{
cout<<"Enter the First No :";
cin>>a;
cout<<"Enter the Second No :";
cin>>b;
}
friend void add(Myclass);
};

void add(Myclass d)
{

d.c=d.a+d.b;
cout<<"Sum of two Integers : "<<d.c;
}

int main()
{
Myclass d;
d.get_int();
add(d);
return 0;
}

OUTPUT

You might also like