Word from the Author

"One mans mistake is another mans break"
Most of the article(s) which I have posted here are based on my own personal experience. Please do not get aggravated if you disagree with what I wrote.This is just my opinion and it might not be worth much. In case you find some errors or mistakes , have any other useful information which others including myself would benefit from or if you like an article you can always post your messages and comments here.

Operator Overloading With Friends...

Some people believe that using friend functions basically disrupts the object orientation in an application giving rise to chaos and mistrust (I guess the words are a bit too harsh .)However there are scenarios in which friend functions could come in extremely handy saving both time and effort. One such example is while using operator overloading.I believe one of the least practiced or followed techniques is operator overloading.This post targets beginner to intermediate developers but if you are an experienced programmer then please feel free to post your views.This article covers how operator overloading could be achieved with friend functions

Consider a simple code scenario in which the operators '+' and '<<' are overloaded .
This is a scenario in which friend functions were used to grant access to private members ..

class class_
{
 private:
  int somenumber;
  friend class_* operator+(class_& RHS,class_& LHS);
  friend ostream& operator<<(ostream& RHS,class_& LHS);
 public:
  class_(int a):somenumber(a){}
};

class_* operator+(class_& RHS,class_& LHS)
{
  class_ *new_class =new class_(RHS.somenumber + LHS.somenumber);
  return new_class;
}


ostream& operator<<(ostream& RHS,class_& LHS)
{RHS << LHS.somenumber;}


void main()
{
class_ objA(30);
class_ objB(40);
class_ *obj = NULL;
obj = objA+objB;//Overloaded
cout << *obj;   //Overloaded
}

2 comments:

  1. technically shouldn't the same code work with private? in that case... why the need for friend?

    ReplyDelete
  2. Hi Hassan , your probably confusing friend functions with class member functions (also known as methods). When a simple function is declared as a friend of a class it then has access to all the data of that class. And if you remove the friend declaration from the class you wont be able to access the private members of the class from that function... Another good article would be http://www.cplusplus.com/doc/tutorial/inheritance/ .

    ReplyDelete