Functions
- Pick out the correct statement.
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
A friend function may or may not be a member of another class
- What is the output of this program?
#include <iostream>
using namespace std;
class Example
{
int W, H;
public:
void set_values (int, int);
int RectArea () {return (W * H);}
friend Example duplicate (Example);
};
void Example::set_values (int p, int q)
{
W = p;
H = q;
}
Example duplicate (Example RectParameter)
{
Example Rect;
Rect.W = RectParameter.W * 2;
Rect.H = RectParameter.H * 3;
return (Rect);
}
int main ()
{
Example Rectangle, RectangleB;
Rectangle.set_values (2, 3);
RectangleB = duplicate (Rectangle);
cout << RectangleB.RectArea();
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
In this program, we are using the friend function for duplicate function and calculating the area of the rectangle.
- What is the output of this program?
#include <iostream>
using namespace std;
class BoxExample
{
double W;
public:
friend void printW(BoxExample box );
void setW( double width );
};
void BoxExample::setW( double width )
{
W = width;
}
void printW(BoxExample box )
{
box.W = box.W * 3;
cout << "Width of box : " << box.W << endl;
}
int main( )
{
BoxExample box;
box.setW(15.0);
printW( box );
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
We are using the friend function for printwidth and multiplied the width value by 3, So we got the output as 45.
- Where does keyword ‘friend’ should be placed?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
The keyword friend is placed only in the function declaration of the friend function and not in the function definition because it is used toaccess the member of a class.
- What is the output of this program?
#include <iostream>
using namespace std;
class Example;
class Example1
{
int W, H;
public:
int Area ()
{
return (W * H);}
void convert (Example p);
};
class Example
{
private:
int side;
public:
void set_side(int p)
{
side = p;
}
friend class Example1;
};
void Example1::convert (Example p)
{
W = p.side;
H = p.side;
}
int main ()
{
Example Square;
Example1 Rectangle;
Square.set_side(5);
Rectangle.convert(Square);
cout << Rectangle.Area();
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
In this program, we are using the friend for the class and calculating the area of the square.