Friday 16 November 2012

C++ Friend function and Friend Class

C++ Friend function and Friend class

In the last C++ programming tutorial we looked at inheritance. In this C++ programming tutorial we will take a look at C++ friendship.

Friend Functions

A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading.
In the following example, the friend function print is a member of class TWO and accesses the private data members a and b of class ONE.

#include <iostream>
using namespace std;

//Must be known to TWO
//before declaration of ONE.
class ONE;

class TWO
{
public:
  void print(ONE& x);
};

class ONE
{
  int a, b;
  friend void TWO::print(ONE& x);
public:
  ONE() : a(1), b(2) { }
};

void TWO::print(ONE& x)
{
  cout << "a is " << x.a << endl;
  cout << "b is " << x.b << endl;
}

int main()
{
  ONE xobj;
  TWO yobj;
  yobj.print(xobj);
}

Friend functions have the following properties:
  • 1) Friend of the class can be member of some other class.
  • 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND.
  • 3) Friend 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.
  • 4) Friends are non-members hence do not get “this” pointer.
  • 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes.
  • 6) Friend can be declared anywhere (in public, protected or private section) 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 class must be first declared or defined (forward declaration).

#include <iostream>
using namespace std;

class MyClass
{
 // Declare a friend class
 friend class SecondClass;

 public:
  MyClass() : Secret(0){}
  void printMember()
  {
   cout << Secret << endl;
  }
 private:
  int Secret;
};

class SecondClass
{
 public:
  void change( MyClass& yourclass, int x )
  {
   yourclass.Secret = x;
  }
};

void main()
{
 MyClass my_class;
 SecondClass sec_class;
 my_class.printMember();
 sec_class.change( my_class, 5 );
 my_class.printMember();
}

Note:we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class SecondClass.
Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.
That is all for this tutorial.
This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use ShareThis to share this post with others.

There are currently 17 responses to “C++ Friend function and Friend class”

Why not let us know what you think by adding your own comment!
  1. karan on March 15th, 2010: hi , can u give me the difference between the friend class and friend function….
  2. admin on March 15th, 2010: The tutorial is clear on this, but here you go, I found this definition on another site:
    A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. A friend class has full access of private data members of another class without being member of that class.
  3. shrihari on June 28th, 2010: can two functions be declared friend to one class?
  4. admin on June 29th, 2010: @shrihari Sure you can declare two functions friend of one class, take a look at an example:
    #include<iostream>
    using namespace std;
    class AClass {
    private:
    int a,b;
    public:
    void test() {
    a=10;
    b=20;
    }
    // Declare the two functions friends.
    friend int add(AClass input);
    friend int minus(AClass input);
    };
    // Function one
    int add(AClass input) {
    return int(input.a + input.b);
    }
    // Function two
    int minus(AClass input) {
    return int(input.b – input.a);
    }
    void main(void){
    AClass output;
    // Initialize output
    output.test();
    cout << add(output) << endl;
    cout << minus(output) << endl;
    }
    I hope this answers your question.
  5. shrihari on June 30th, 2010: Thank u. It works!!
  6. hemed on May 18th, 2011: why the argument or parameter of a friend function must be of the type of Aclass
    eg from the code above
    // Declare the two functions friends.
    friend int add(AClass input);
    friend int minus(AClass input);
    am confused with this please help me
  7. silu on June 13th, 2011: friend function can access the private members of class. Is it possible, so that friend function should not access the private members of a class? Is any concept deals with it.
  8. Yash Bawne on September 24th, 2011: We consider that friend function access the private data member of the class.But I did’nt get actually ,because member function of the class also use private data directly.
    Plese clarify that…
  9. veena bopche on November 9th, 2011: can we make more than one friend functions within a class?
  10. tek on December 2nd, 2011: C++ :Can we access private function of class from another class(not friend or inherited) without using public function?I mean Class A has private function A1.Can we access A1 from another class B directly using pointer.You cannot use public function in class A to return address of private function A1.class B is not friend or child of class A.
    -Tek
  11. SHAGUN on January 17th, 2012: worth!!!!!!!!!!!
  12. Reshma on February 8th, 2012: wat is the output for the program friend class… :-|
  13. elite leena on February 24th, 2012: @reshma
    the output is
    0
    and
    5

4 comments:

  1. A reliable web development Dubai service holds paramount importance to create the strong online presence.
    If you are done with your schooling, you can get admitted for diploma
    or under graduation in the course. There are many email marketing consulting companies but they are good in talking and telling you
    what to do.

    Here is my homepage The Design Entrepreneur Free Download

    ReplyDelete
  2. And when you begin tossing $20 at clientele for spreading the
    word about your DJ business, they will commence marketing for you a lot more often.
    Daft Punk - Harder Better Faster Stronger There's something intriguing about a robotic voice egging you on. Music situation serves as a "vocation sponsor" for outside the box musical performers.

    my blog: random access memories daft punk download rar

    ReplyDelete
  3. , Is Muscle Maximizer a sham or does it sincerely work. If you would definitely be a
    true beginner to figuring out to gain muscular, you will need to begin your
    workouts inside the gym or health and fitness center to use trainers and other staff to support
    and teach anyone setup your schooling routine.

    Who is this Somanabolic Muscle Maximizer Training Software Designed For.



    Visit my weblog - Somanabolic Muscle Maximizer Reviews

    ReplyDelete
  4. In the beginning of the 11th Century the represents of Christianity is able to banned the duel form einvigi and holmgangr as
    lawfully accepted means to solve a dispute, and at
    the same time the berserkr and the beserksgangr was
    made illegal. The adobe reader is what you need to download e - Book in PDF format.

    It is sold through Click - Bank, considered the internet's most trusted digital marketplace.

    My blog :: free pdf ebook download

    ReplyDelete