Write the Method Bodies
Write similar bodies for slice() and juice() for the Fruit class. Copy the body of
peel to start with.
- In a real system, these methods would presumably operate a robot arm to
carry out the desired fruit preparation. In this training exercise, just make
each method print out the fact that it has been invoked. - Give these methods likely parameters and return types. For example,
slice() should take an integer parameter indicating the desired number of
slices, juice() should return a float value representing the number of cc's
of juice obtained, and so on. The prototypes in the class definition will have
to match the function definitions, of course. - Try accessing data in the private part of the class, from inside a method and
then from outside.
How to Call a Method
Look at the interesting way to call a function within a class. You have to prefix it with the instance, or
class variable, you want it to operate on.
Fruit melon, orange, banana;
main() {
melon.slice();
orange.juice();
return 0;
}
Then the object does that operation on itself. It's quite similar to some predefined operators; when we
write i++ we are saying "take the i object and do the post-increment operation on it." Invoking a
member function on a class object is equivalent to the "sending a message to that object" terminology
that other object-oriented languages use.
Every method has a this pointer parameter implicitly passed to it, allowing an object to refer to itself
inside a method. Note how the explicit use of the this pointer can be omitted when inside a member
function, and it is assumed.