Suppose your program contains the following class definition:
class Automobile
{
public:
void set_price(double new_price);
void set_profit(double new_profit);
double get_price( );
private:
double price;
double profit;
double get_profit( );
};
and suppose the main part of your program contains the following
declaration and that the program somehow sets the values of all the
member variables to some values:
Automobile hyundai, jaguar;
Which of the following statements are then allowed in the main part of
your program?
hyundai.price = 4999.99;
jaguar.set_price(30000.97);
double a_price, a_profit;
a_price = jaguar.get_price( );
a_profit = jaguar.get_profit( );
a_profit = hyundai.get_profit( );
if (hyundai == jaguar)
cout << "Want to swap cars?";
hyundai = jaguar;
Let's analyze each statement to determine whether it is allowed in the main part of the program:
hyundai.price = 4999.99;
price
member variable is declared as public
, it can be directly accessed and modified.jaguar.set_price(30000.97);
set_price()
function is a public member function, which allows setting the price
member variable.double a_price, a_profit;
double
variables a_price
and a_profit
.a_price = jaguar.get_price();
get_price()
function is a public member function, which allows accessing the price
member variable.a_profit = jaguar.get_profit();
get_profit()
function is declared as private
, which means it can only be accessed from within the class and not from outside.a_profit = hyundai.get_profit();
get_profit()
is a private member function, so it cannot be accessed from outside the class.if (hyundai == jaguar) cout << "Want to swap cars?";
==
) defined for the Automobile
class, so you cannot directly compare two Automobile
objects using ==
.hyundai = jaguar;
=
) is not defined explicitly for the Automobile
class, so you cannot directly assign one Automobile
object to another.In summary, the allowed statements are:
hyundai.price = 4999.99;
jaguar.set_price(30000.97);
double a_price, a_profit;
a_price = jaguar.get_price();
Please note that the above analysis assumes the program sets the member variables price
and profit
to public access. If they are private, then direct access to price
would not be allowed, and you would need to use the public member functions to set and retrieve their values.