What are Friend Functions and Friend Classes in C++ ?

October 28, 2007 · Filed Under C++ Questions, Placement Questions 



Don't want to miss a single bit? Subscribe By Email for Daily Jobs

Enter your email address :

All the latest from JobsAdda on Jobsadda.com delivered to your mailbox everyday.

A friend can be a function, another class or individual member function of a class. With the help of a friend function it is possible to grant a non member function access to the private members of a class using a friend.

A friend function has all access to all the private and protected members of the class for which it is the friend. To declare a friend function includes the function prototype within the class preceding it with the keyword friend. When a friend function is called it need to be qualified by the object name as it is not a member function of the class. E.g.

class Complex
{
private:
float real;
float imaginary;
public:
friend Complex operator+ (Complex, Complex);
};
//overloaded + operator for class Complex
Complex operator+ (Complex c, Complex d)
{
Complex tmp;
tmp.real = d.real + c.real;
tmp.imaginary = d.imaginary + c.imaginary;
return temp;
}

To call the function:

int main ()
{
Complex a, b, c;
a = b + c; //this will be called as operator+(b, c)
}

Friend classes are used when two or more classes are designed to work together and need access to each other’s implementation. E.g. a class DataBaseCursor may want more privileges to the class Database. E.g.

class DatabaseCursor;
class Database
{
//member variable and function declarations
friend DatabaseCursor;
};

Related Articles


Get Latest JobsAdda.com Jobs, news & updates  via Email