Home > DeveloperSection > Blogs > Friend function and friend class in C++

Friend function and friend class in C


.NET Visual C++ 
Ratings:
0 Comment(s)
 771  View(s)
Rate this:

Friend function and friend class in C++

In this blog, I’m explaining about friend function and friend class in C++

 

Friend function

1. Friend function can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.

2. Friend can be declared anywhere in the class.

Friend class

A class can also be declared to be the friend of some  other class. When we create a friend  class then all the member functions of the  friend class also become the friend of the other class. This  requires the condition that the friend  becoming must be first  declared or defined.

Example:

// FriendProgram.cpp : main project file.

 

#include "stdafx.h"

#include <iostream>

using namespace std;

using namespace System;

class ADemo

{

public:

 

//Declare  a friend class

            friend class DriveClass ;

            void get()

            {

                        cout<<"Enter two values";

                        cin>>val1>>val2;

            }

            //Declare a friend function

            friend float mean(ADemo objDemo);

            ADemo();

            ~ADemo();

private:

int val1,val2;

 

};

class DriveClass

{

public:

            //Access private members using reference

            void change(ADemo obj)

            {

                        obj.val1=20;

                        cout<<"val1=";

                        cout<<obj.val1;

           

            }

 

};

float mean(ADemo objDemo)

{

            return float(objDemo.val1+objDemo.val2)/2;

}

ADemo

::ADemo

()

{

}

 

ADemo

::~ADemo

()

{

}

 

int main(array<System::String ^> ^args)

{                       ADemo obj;

      obj.get();

              cout<<"\n mean value is :"<<mean(obj);

            DriveClass dreobj;

            dreobj.change(obj);

              Console::ReadKey(0);

    return 0;

}

 


Don't want to miss updates? Please click the below button!

Follow MindStick