Wednesday, June 18, 2008

Friend classes

A method declared as a friend to a class can access the non-public members and methods of that class, as well as the public members and methods of that class.
In order to allow an external function to have access to the private and protected members of a class a prototye of the external function preceded by the keyword 'friend' should be declared within the class that shares its members.

From the classes described in the Operator Overloading example

Number operator+(const float i, const Number f)
{
Number temp;
temp.number = f.number;
temp.num = f.num + abs(i);
return temp;
}
int main() {
Number a(2), c;
c = 4.123 + a;
c.print(); // output will be 4 + 2= 6
}

Friend classes (friend)
We can also define a class as friend of another one, allowing the second one access to the protected and private members of the first.

class Square; // pre decleration
class Rectangle
{
int width, height;
public:
int area (void) {return (width * height);}
void convert (Square a);
};

class Square
{
int side;
public:
void set_side (int a) {side=a;}
friend class Rectangle;
};

void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}

int main () {
Square sqr;
Rectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area(); // will print 16
return 0;
}

Rectangle is a friend of Square so Rectangle can access the protected and private members of Square, more concretely Square::side, that defines the square side width.

No comments: