Avoiding Friends



next up previous
Next: Safe File Pointer Up: TECHNIQUES AND EXAMPLES Previous: NoPredefines

Avoiding Friends

 

Friends are commonly used in C++ to allow global operators access to attributes of a class. Consider the following example.

[ 1]   class ComplexNumber
[ 2]   {
[ 3]   private:
[ 4]       float real, img;
[ 5]   public:
[ 6]       ComplexNumber(float r) {real = r; img = 0.0}
[ 7]       ComplexNumber operator+ (ComplexNumber b) { ... }
[ 8]   };
[ 9]   
[10]   ComplexNumber operator+(ComplexNumber a, ComplexNumber b)
[11]   {
[12]       return (a.operator+(b));
[13]   }
[14]   
[15]   main()
[16]   {
[17]       ComplexNumber a(5);
[18]       a = a + 3.0;
[19]       a = 4.0 + a;
[20]   }

Without the operator on Line [10], the addition on Line [18] is allowed, but the addition on Line [19] cannot be resolved by the compiler and therefore produces an error: On Line [18], the 3.0 is passed to the constructor on Line [6] resulting in the ComplexNumber, 3.0+0.0i, which is then passed to Complex::operator+. On the other hand, for Line [19] there is no function in class float that takes a ComplexNumber1.