Programming and Graphics

(Kiana) #1

164 Introduction to C++ Programming and Graphics


string readcolor(bool Iprint) const;
void changecolor(string newcolor);
private:
string color, shape;
float size;
};

The functionpackagenow has access tocolor,shape,andprice. We will
implement this function as:


//--- FRIEND FUNCTION

void package(fruit item)
{
if(item.size<1.0)
cout << "box" << endl;
else
cout << "crate" << endl;
}

We may then state in the main program:


fruit watermelon("green", "oval", 12.0);
package(watermelon);

The second statement will print on the screen:


box

We recall that, if we want to disclose a private field of an object toall
non-member functions, we must declare it as public.


Problems


6.6.1.Implement a friend function that determines whether the color of a fruit
is green.


6.6.2.Implement a friend function that determines whether the size of a fruit
is less than 3.0 inches.


6.7 Circlesandsquares..........................


To further illustrate the concept of private variables, we consider a code defining
two classes, one containing circles and the second containing horizontal squares.

Free download pdf