Friends
Explore how friend declarations in class templates allow controlled access to members. Understand general and special friend templates, their rules, and how friendship applies to types for managing encapsulation and access in advanced C++ programming.
We'll cover the following...
Friends
Friends of a class template have access to all members of the class template.
A class or a class template can have a friendship to class or class templates, function or function templates, and types.
Rules:
- The declaration of friends can be made at an arbitrary place in the class declaration.
- The access rights in the class have no influence.
- Friendship will not be inherited.
- Friendship is not transitive.
A friend has unrestricted access to the members of the class.
General Friends
A class or a class template can grant friendship to each instance of a class template or a function template.
When a class template grants friendship to a template, the
typenameof the class template should be different from thetypenameof the template. If both use the same name, the friendship is only granted for the same types.
Special Friends
A special friendship is a friendship that depends on the type of the template parameter.
If the name of the template parameter is identical to the name of the template parameter granting the friendship, the friendship will be between instances of the same type.
Friend to Types
A class template can grant its friendship to a type parameter.
template <typename T>
class Array{
friend T;
...
};
Array<Account> myAccount;
To know more about friends, click here.