Tip:
Highlight text to annotate it
X
In this lesson, we're going to take a look at the bracket operator. The bracket operator is a little bit different.
You pass arguments to it in a little bit different fashion. So, let's take a look. We're gonna do a code trace. Here in main we're going to declare a
fraction with numerator three and denominator four and then I'm going to output
'f' of four, 'f' of one and 'f' of five. So, what do we mean by 'f' of anything?
Well, the bracket operator, also known as the projection operator, is typically used for indexing. So, this example is a bit contrived, I know.
What we're gonna do is we're going to define the bracket operator to index into
a fraction object. So, the way we define it is to return an int that's going to be either a numerator or
denominator. It's scoped as a fraction of course,
and we pass to it an int called 'index'. It's a const function because it's not going to change
anything with the calling object. And what's it going to return? Well, if the index that passed to the function
is zero we're going to return the numerator and otherwise we'll return the denominator of the calling object. So, 'f' of zero that should return
what? That should return the numerator, or in this case, 3.
'f' of 1, well, the argument that we're passing is 1. That's what goes in for index here. That's not zero therefore this should return the denominator.
And 'f' of five, that should return the denominator also. Output should be 3, 4 and 4. So let's go through
a code trace and see what it looks like. Fraction is 3/4, numerator is 3, denominator is 4.
So we're going to take a look first at 'f' of 5. We call the function, index is 5, that returns the denominator and we put 4 into the output buffer.
Then a space, then we're going to call 'f' bracket operator passing one,
index is one, that's not zero, so we return the denominator. So, 4 goes into the output buffer,
then a space and then 'f' of 0. So we are passing zero in as the index. So index is zero, that means we're gonna return the numerator
and so we'll return and output the numerator which is 3. So, when the output buffer is flushed, we end up with 3, a space, 4 and then 4.
And here's a bunch of wookies...
And that's the end of our session.