blog

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

Friend function and friend class in C++

priyanka kushwaha2397 30-Jan-2015

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>
usingnamespace std;
usingnamespace System;
classADemo
{
public:
 
//Declare  a friend class
            friendclassDriveClass ;
            void get()
            {
                        cout<<"Enter two values";
                        cin>>val1>>val2;
            }
            //Declare a friend function
            friendfloat mean(ADemo objDemo);
            ADemo();
            ~ADemo();
private:
int val1,val2;
 
};
classDriveClass
{
public:
            //Access private members using reference
            void change(ADemoobj)
            {
                        obj.val1=20;
                        cout<<"val1=";
                        cout<<obj.val1;
           
            }
 
};
float mean(ADemoobjDemo)
{
            returnfloat(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;
}

 


Updated 30-Jan-2015

Leave Comment

Comments

Liked By