accessing private member of a friend class with a friend function

Hello, I was reading code and I saw a friend function access a protected member of a friend class. To be more specific, I saw a friend function in a matrix class access the private members of a vector class.

1
2
3
4
5
6
// a friend function in the matrix class accessing the protected members of my Vector3 class
Vector3 operator*(float scalar, const Vector3& vector)
{
    return Vector3(scalar*vector.x, scalar*vector.y, scalar*vector.z);

}


I tried writing a matrix class this way but it won't compile, I can't access the private members of a friend class with a friend function. Now I know this is possible because it is done in the source files I'm reading, I'm still reading the code, trying to figure out how it works, bit I thought I'd post it here, maybe someone will answer.
Friendship is not transitive, neither symmetric. (neither inherited, but see below)

Not transitive:
A function f is friend of class C. This means f can access all members of C that C itself can access. C is friend of class D. Therefore members of C can access all members of D that D itself can access. Still, f can not access private and protected members of D.

Not symmetric:
If class C is friend of class D, but not vice versa, then C can access all members of D that D itself can access, but D will still not be able to access the private and protected members of C (access of inherited members excepted from the last).

The only way for some function to access the private and protected members of some class is to be declared explicitly friend of that class (in the definition of the class), or to be declared friend of some base class and to work with the base class data through pointers and references. The latter is rarely used, and should not be used to break encapsulation.

In other words, the function had to be declared friend of the vector class.

Regards
Last edited on
Yes, that was it! thanks a lot.
Topic archived. No new replies allowed.