friend function
   HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, a friend function, that is a "friend" of a given
class Class, Classes, or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used d ...
, is a function that is given the same access as methods to private and protected
data Data ( , ) are a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted for ...
. A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods. Friend functions allow alternative syntax to use objects, for instance f(x) instead of x.f(), or g(x,y) instead of x.g(y). Friend functions have the same implications on encapsulation as methods. A similar concept is that of friend class.


Use cases

This approach may be used in friendly function when a function needs to access private data in objects from two different classes. This may be accomplished in two similar ways: *A function of global or
namespace In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
scope may be declared as friend of both classes. *A method of one class may be declared as friend of another one. // C++ implementation of friend functions. #include using namespace std; class Foo; // Forward declaration of class Foo in order for example to compile. class Bar ; class Foo ; // Definition of a method of Bar; this is a friend of Foo void Bar::show(Bar& x, Foo& y) // Friend for Bar and Foo, definition of global function void show(Bar& x, Foo& y) int main()


References

{{reflist *
The C++ Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the C programming lang ...
by
Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, known for the development of the C++ programming language. He led the Large-scale Programming Research department at Bell Labs, served as a professor of computer sci ...


External links


C++ friend function tutorial
at CoderSource.net Method (computer programming) Articles with example C++ code