"C++ - Where only your friends can access your private parts" | ||
--Unknown, 1991 |
In C++ normal access control has the keywords:
private
- only accessible within the class.
protected
- only accessible within the class and its derived
classes.
public
- accessible anywhere.
A class can declare a method to be a friend, allowing that method to access private
and protected
members (friendship is granted! Not acquired.). For example:
class SomeClass { private: int x; friend void someMethod(SomeClass &); public: // the interface }; // This method is somewhere! void someMethod(SomeClass &a) { a.x = 5; //allowed! }
It is important to note that someMethod()
is not a member method of
the class SomeClass
. i.e. It does not have scope within the class
SomeClass
.
So if we tried:
SomeClass b; b.someMethod();
This is illegal, as someMethod()
is not a member method of the
SomeClass
class (and it is not public).
Friend Methods are useful as:
Friend methods avoid adding unnecessary public methods to the interface.
Prevent states from having to be made public.
However, the overuse of friend methods can make the code very complex and hard to follow.
We can add all the methods of a class as friends of another:
class A { private: int x; friend class B; public: //methods here };
Friendship is not inherited:
class B { x(A &a) //some method that is passed an object of A { a.x++; //fine } }; class C: public B // class C is a child of B { y(A &a) //some method that is passed an object of A { a.x++; //illegal } };
Friendship is not transitive:
class AA { friend class BB; }; class BB { friend class CC; }; class CC { // Not a friend of AA };
© 2006
Dr. Derek Molloy
(DCU).