Download 8. Intro to Object
Transcript
She can do this because initialize is a public member
function, and even public member functions have
access to the class’s own private variables!
8.6 Initializing Member Attributes
Since the private members are not accessible, you
might ask how they get values.
If they were public, you could as shown in your text do:
AirPosition pos5 = {-123.,49.,28000};
But this doesn’t work if the attributes are private.
You could write and export a public member function
like:
Note that an initialization function, or a constructor (as
discussed next) can be used to initialize non-private
member functions. Such functions can also do useful
work other than just setting variables.
class AirPosition{
private:
float latitude;
float longitude;
long altitude;
public:
void initialize( float latParam,
float longParam,
long altParam){
latitude = latParam;
longitude = longParam;
altitude = altParam;
}
void drop(int dropHeight){
altitude = altitude - dropHeight;
}
};
A client programmer could then use:
Airposition pos6;
pos6.initialize(123.,49.,28000);
Copyright 1998 by R. Tront
8-21
Copyright 1998 by R. Tront
8-22