Understanding friendship in templates
When you define a class, you can restrict access to its member data and member functions with the protected
and private
access specifiers. If a member is private, it can only be accessed within the class. If a member is protected, it can be accessed from derived classes with public or protected access. However, a class can grant access to its private or protected members to other functions or classes with the help of the friend
keyword. These functions or classes, to which special access has been granted, are called friends. Let’s take a look at a simple example:
struct wrapper { wrapper(int const v) :value(v) {} private: int value; friend void print(wrapper const & w); }; void print(wrapper const& w) { std::cout << w.value << '\n'; } wrapper w{ 42 }; print(w);
The wrapper
class has a private data member called value
. There is a free...