Function and Method - Object oriented programming (MCQ) questions for Q. 3
Q. Give output of the following:
#include <iostream>
using namespace std;
class exam
{ private:
int x, y, z;
public:
int testcase( )
{
x=50; y=20; z=30;
}
friend int add( exam e);
};
int add( exam e)
{
return int( e.x+ e.y+ e.z);
}
int main( )
{
exam a;
a.testcase( );
cout << add(a);
return 0;
}
- Published on 19 Oct 15a. 0
b. compile time error
c. 100
d. none
ANSWER: compile time error
This code shows usage of a friend function and how a friend function has access to private members of a class. Generally a function defined outside the class cannot access the private and protected members of the class but by declaring a function as friend function the class gives it permission to access its private and protected data.