Sunday, April 4, 2021

Friend classes in c++ (OOP) (14)

            /*Friend classes in c++

                                ***********************/

/* when a class made a friend class.all the member function of that class become the friend 

function of that class.in this program all member function of class A will be the friend function

of class B. so any member function of class B can access the private and protected data of class A.

 */


// C++ program to demonstrate the working of friend class


#include <iostream>

using namespace std;


// forward declaration

class B;


class A {

    private:

        int a;


    public:

        A(int x)

{

a=x;

}

// friend class declaration

        friend class B;

};


class B {

    private:

        int b;


    public:

        B(int y)

{

b=y;

}

    int add() 

{

        A obj1(10);

        return obj1.a + b;

    }

};


int main() 

{

    B obj2(4);

    cout << "Sum: " << obj2.add();

    return 0;

}

No comments:

Post a Comment