Friday, 22 November 2013

C++ Class Members and Friends

C++ Class Members and friends

Introduction

This article tells us how to grant access to its non public members by the use of friend mechanism.

Friend Mechanism

  • A friend of a class X is a function or class that is not a member of X, but is granted the same access to X as the members of X
  • Functions declared with the friend specifier in a class member list are called friend functions of that class
  • Classes declared with the friend specifier in the member list of another class are called friend classes of that class.
  • A class Y must be defined before any member of Y can be declared a friend of another class.
  • We can define a function as a friend or an entire class as friend. The function can be a member of a class or declared in the global namespace. The function needs to be declared before it can be used as friend.
  • If a friend function is a member of another class,a scope resolution operator needs to be used ,for example Y::print(X\& x);
  • however a function can be defined provided function is unqualified and has namespace scope (function is not a member of function of another class or declared in another workspace) and class is non local.
  • If a class F is a friend of class A,then every member function and static data member definition of class F has access to class A.
  • For using the class as a friend,in the declaration must be elaborated class name , for example friend class F
  • A friend class can be defined after it is declared as friend in other class
  • A friend cannot be declared with a storage class specifier.
  • A class cannot be defined within a friend declaration,
  • The scope of a friend class name is the first nonclass enclosing scope In the example the scope of the friend class name is class Z1 and not class
  • Friends of a base class are inherited by any classes derived from that base class The functionality that the friend of the base class are inherited by the derived by the base class may be compiler dependent.The g++ compiler on Linux supports this feature,while many online references suggest this inheritance does not hold.
  • If a class is derived from a friend class ,then it is also a friend of the original base class.This feature may also be compiler dependent.The g++ compiler on Linux supports this feature,while many online references suggest this inheritance does not hold.
  • Friendships are not transitive if A is a friend of B,and C is a friend of A,it does not imply that C is a friend of B unless explicitly specified.

code

The code used in the article can be found in Git repository https://github.com/pi19404/m19404/tree/master/CPP/t1