1

friend keyword

Question 1
Predict the output of following program.
#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;
}
A
Compiler Error in show() because x is protected in class A
B
Compiler Error in show() because y is private in class b
C
The default value of A::x = 0 The default value of B::y = 0
D
Compiler Dependent
friend keyword    
Discuss it


Question 1 Explanation: 
Please note that show() is a friend of class A, so there should not be any compiler error in accessing any member of A in show(). Class B is inherited from A, the important point to note here is friendship is not inherited. So show() doesn't become a friend of B and therefore can't access private members of B.
Question 2
Predict the output the of following program.
#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;
}
A
Compiler Error
B
A::a=10 B::b=0
C
A::a=0 B::b=0
friend keyword    
Discuss it


Question 2 Explanation: 
This is simple program where a function of class A is declared as friend of class B. Since show() is friend, it can access private data members of B.
There are 2 questions to complete.
1

Company Wise Coding Practice    Topic Wise Coding Practice