Saturday, August 25, 2007

Friend Function

The private member data of a class can be accessed only by the class member functions. Well there is one exception in C++ language. A friend function will be friendly with a class even though it is not a member of that class. A friend function is allowed to access the private members of that class.

Basically, its violating the encapsulation. But it improves the code.

Thinking in such a way that a bigger problem is broken into halves.


How the friend function is called???

The friend function is called like f(x), while a member function is called x.f().





Example:


#include
using namespace std;

class Car
{
private:
int speed;
char color[20];

public:
Car()
{
speed=20;
strcpy(color,"red");
}
friend void display(Car& c);
};
void display(Car& c)
{
cout<< c.speed;
cout<< c.color;
}


void main()
{
Car c;
display(c);
}

No comments: