C++ Friend Keyword

October 27, 2015 Posted by WithU Technologies
As we know the Encapsulation rules that there are different Access specifiers to access certain objects and variables.

Private specifiers cannot be accessed from outside the class.

But if we use the friend keyword as prefix before a non- member external function then we can access the private members.

#include <iostream>
using namespace std;

class Keyword{     // A class is Declared

public:

      Keyword()      //Regular Constructor initialized without any parameters

      {

    x=10;

    y=46;

    cout<<"Before Modification: "<<x+y<<endl;  //Two integer variable initialised with values and we also have their sum as output here

      };

private:           //Two integer variables are initialised under the private encapsulation

      int x;

      int y;

friend void NewKeyword(Keyword &NewOb);   //friend keyword is used to access the Keyword class from outside

};

void NewKeyword(Keyword &NewOb){    //NewKeyword function took Keyword class as its parameter and pass it by reference to NewOb object using ampersand (&) operator

      NewOb.x = 12;    //New value is assigned to x variable  using dot operator

      NewOb.y = 25;    //New Value is assigned to y variable

      cout<<"After Modification: "<<NewOb.x+NewOb.y<<endl;  //New Output after using the new values

}

int main() {

      Keyword NewOb;   //NewOb object is created under Keyword class

      NewKeyword(NewOb);   //it pass the new value by reference of NewOb object

}

·         Initially we use the public class to access the private members and then use those members to output the summation. Thus we get an output as Before Modification

·         As we can see here in the example shown above, a NewKeyword function is declared outside the public class as an external function.

·         We use the friend keyword as prefix before that external function and it will provide a link to access the private members and thus we can modify those members with new values which provide a new result.