• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests

C++ friend keyword

Question 1

Predict the output of following program. CPP
#include <iostream>
using namespace std;
class A
{
protected:
    int x;
public:
    A() {x = 0;}
    friend void show();
};

class B: public A
{
public:
    B() : y (0) {}
private:
    int y;
};

void show()
{
    A a;
    B b;
    cout << \"The default value of A::x = \" << a.x << \" \";
    cout << \"The default value of B::y = \" << b.y;
}
  • Compiler Error in show() because x is protected in class A
  • Compiler Error in show() because y is private in class b
  • The default value of A::x = 0 The default value of B::y = 0
  • Compiler Dependent

Question 2

Predict the output the of following program. 

C
#include <iostream>
using namespace std;

class B;
class A {
    int a;
public:
    A():a(0) { }
    void show(A& x, B& y);
};

class B {
private:
    int b;
public:
    B():b(0) { }
    friend void A::show(A& x, B& y);
};

void A::show(A& x, B& y) {
    x.a = 10;
    cout << \"A::a=\" << x.a << \" B::b=\" << y.b;
}

int main() {
    A a;
    B b;
    a.show(a,b);
    return 0;
}
  • Compiler Error
  • A::a=10 B::b=0
  • A::a=0 B::b=0

Question 3

If a function is friend of a class, which one of the following is wrong?
  • A function can only be declared a friend by a class itself.
  • Friend functions are not members of a class, they are associated with it.
  • Friend functions are members of a class.
  • It can have access to all members of the class, even private ones.

Question 4

Which one of the following is correct, when a class grants friend status to another class?
  • The member functions of the class generating friendship can access the members of the friend class.
  • All member functions of the class granted friendship have unrestricted access to the members of the class granting the friendship.
  • Class friendship is reciprocal to each other.
  • There is no such concept.

There are 4 questions to complete.

Last Updated :
Take a part in the ongoing discussion