C++ Friend Question:
Download Questions PDF

What is the output of this program?

#include <iostream>
using namespace std;
class sample
{
int width, height;
public:
void set_values (int, int);
int area () {return (width * height);}
friend sample duplicate (sample);
};
void sample::set_values (int a, int b)
{
width = a;
height = b;
}
sample duplicate (sample rectparam)
{
sample rectres;
rectres.width = rectparam.width * 2;
rectres.height = rectparam.height * 2;
return (rectres);
}
int main ()
{
sample rect, rectb;
rect.set_values (2, 3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}

a) 20
b) 16
c) 24

C++ Friend Interview Question
C++ Friend Interview Question

Answer:

c) 24
Explanation:
In this program, we are using the friend function for duplicate function and calculating the area of the rectangle.
Output:
$ g++ friend1.cpp
$ a.out
24

Download C++ Friend Interview Questions And Answers PDF

Previous QuestionNext Question
What is the output of this program?

#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid )
{
width = wid;
}
void printWidth( Box box )
{
box.width = box.width * 2;
cout << "Width of box : " << box.width << endl;
}
int main( )
{
Box box;
box.setWidth(10.0);
printWidth( box );
return 0;
}

a) 40
b) 5
c) 10
d) 20
What is the output of this program?

#include <iostream>
using namespace std;
class sample;
class sample1
{
int width, height;
public:
int area ()
{
return (width * height);}
void convert (sample a);
};
class sample
{
private:
int side;
public:
void set_side (int a)
{
side = a;
}
friend class sample1;
};
void sample1::convert (sample a)
{
width = a.side;
height = a.side;
}
int main ()
{
sample sqr;
sample1 rect;
sqr.set_side(6);
rect.convert(sqr);
cout << rect.area();
return 0;
}
a) 24
b) 35
c) 16
d) 36