Tip:
Highlight text to annotate it
X
In this lesson, we're gonna take a look at friend functions. What's a friend function? What's it gonna do for us? Let's take a look at, revisit our
old problem of direct access to the private member variables of a class, in this case the fraction class. We tried to write a global function
"mult_fracs" where inside we attempted to directly access the private member variables of the class. And so what happened? Well, it didn't
work. That's not legal. We simply can't directly access those private member variables. So, what we did was we built some
accessor/mutator functions to help us out. Well, you know that's kinda cumbersome at times and there's a quicker, easier way to deal with the
problem. That is to use a friend function. So, what's a friend function?
Well, a function is a friend function if it has been designated by the class to be a friend function of the class.
That means it's given direct access rights to the private members section of the class.
The key word "friend" will never be used outside of the class. It always is used inside the class. The class that is
designating the friendship, that is giving the access to its private
section. So, you never want to use the word friend outside of a class. In our example, we're going to
declare the prototype inside of the class. We're going to declare, as a friend, this function called
"mult_fracs". It returns a fraction and takes to fractions as arguments.
Here's the definition of it. Notice that it is not scoped here as a member function of the class. It's a global function. This access,
all of these, right here, are now legal. Even though this is a non-member function, because it has been granted friendship to the fraction class,
it has direct access rights to private member variables of that fraction class.
So, it works. Everything is fine. Everything is hunky-dory, but there's one thing that you don't want to do.
You do not want to put that word friend outside of the class. Now here's the full function definition. Again,
we declared it as a friend and here's the definition where I have declared a temporary fraction,
I've built that temporary and then I return that temp. No friend outside here, you only put friend inside. Putting friend outside the class definition,
like this, is not acceptable. It won't compile, it doesn't make any sense.
That's sort of like saying that this is a friend to the entire world. You don't want to do such a thing. Bad thing to do!
Okay, so now you know what a friend of the class is. You should use that sparingly.
Remember that it creates a hole in your security system. You should never use a friend unless you absolutely have
to. There are cases where you do. One example is the
insertion operator. It's most convenient if you make it a friend and we'll take a look at it later.
For now, that's the end of this session.