Programming and Graphics

(Kiana) #1

160 Introduction to C++ Programming and Graphics


public:
fruit();
fruit(q, w, ..., e);
~fruit();
string readcolor(a, b, ..., c) const;
void change(g, o, ..., x);
private:
string color;
string shape;
float size;
};

If we want to make the color of a fruit available to the main program and any
other function that uses objects of the fruit class, we must move the declaration:


string color;

to the public section of the class definition.


Suppose, for example, that a functionoutsidethe fruit class declares

kiwi = fruit();

Ifcoloris a private field, the statement:


cout << kiwi.color;

is unacceptable. However, ifcoloris a public field, this statement is perfectly
acceptable. Class member fields are routinely kept private to prevent inadver-
tent evaluation in unsuspected parts of a code.


Before proceeding to discuss specific class implementations, we emphasize
two important properties regarding variable availability:



  • The arguments of the constructor that defines an object, whether public
    or private, are implicitly available to the member functions. Thus, the
    calling arguments of a member function operating on an object include
    by default the arguments of the constructor that defines the object.


For example, suppose that thevendormember function has been defined
as:

void fruit::vendor()
{
...
}
Free download pdf