C++ | Friend function 12

C++ Programming Questions and Answers – Friend Functions

This section on C++ MCQs (multiple choice questions) focuses on “Friends Functions”. One shall practice these MCQs to improve their C++ programming skills needed for various interviews (campus interviews, walk-in interviews, company interviews), placements, entrance exams, and other competitive exams.
These questions can be attempted by anyone focusing on learning C++ programming language. They can be a beginner, fresher, engineering graduate, or an experienced IT professional. Our multiple-choice questions come with a detailed explanation of the answers which helps in a better understanding of C++ concepts.

1.
Which rule will not affect the friend function?

a) private and protected members of a class cannot be accessed from outside
b) private and protected member can be accessed anywhere
c) protected member can be accessed anywhere
d) private member can be accessed anywhere

2.
Which keyword is used to declare the friend function?

a) firend
b) friend
c) classfriend
d) myfriend

3.
What is the syntax of friend class, written in class “class1”?


a) friend class Class2;
b) friend class;
c) friend class
d) friend class()


4.
What will be the output of the following C++ code?

#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


5.
What will be the output of the following C++ code?

#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
d) 18


Number Of Visitors

0270407