-
Friends and Members
Ok, so I googled to see if I can see what the difference is between friends and members of a class, but all sites seem a little hazy....
I think a friend has all the power of a member, so why delcare it as a friend and not as a member? and what is the difference in declaring a friend from a member?
Thanks!
-
Friends and members are not the same thing.
You can declare a class or a function (B) or a function (B) or another class (B) a friend of one class (A), in which case that function (B), class (B) or class member (B) will have full access to the class (A), including privately declared data.
-
ok... I think I follow. what is the difference between the declaration statements of a friend and of a member...
-
Well, as I mentioned, they're not the same.
Code:
class foo
{
friend class foo2; // Friend declaration
static void foo(); // Member declaration
};
class foo2
{
public:
void foo() { foo::foo(); } // Legal since foo2 is a friend of foo.
};
-
ok- lets say I want to write the following friend statement as a member function instead
Code:
friend Pairs operator *(const Pairs& f, const Pairs& s);
will it be something like
Code:
void Pairs operator*();
Im still really confused about friends and members
-
No, the friend keyword is a keyword applied to a declaration in cases of functions.
Define your function as
Code:
Pairs operator *(const Pairs& f, const Pairs& s);
And inside the class, add the friend declaration:
Code:
friend Pairs operator *(const Pairs& f, const Pairs& s);
The operator * will now have access to the class internals.
-
A member is (as it says) part of the class. A friend is not part of the class, it belongs to something else entirely (or nothing at all), but the class has granted it access to the data.
Your operator * will still return a Pairs element (I'm assuming -- it did before), it certainly won't return void. And you will still need to specify the right hand side of * -- you have to multiply your object by something.