[cs23021] Lab 9 Problem

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Oct 28 11:15:59 EDT 2010


> 
> I came upon another annoying problem, and that was the
> function deployShip. The problem was the I could not access the
> ship's loc.x and loc.y to set them as the parameter's position. I
> tried creating a set function within location that sets the
> coordinates of the location, but this also gave me an error.
> 
> my code originally looked something like this:
> ship::deployShip(location position){
> loc.x = position.x;
> loc.y = position.y;
> }
> 
> when modified, looked like this:
> ship::deployShip(location position){
> loc.set(position.x, position.y);
> }
> 
> This too gave me an error saying that position.x's privacy had been
> violated. It seems you cannot pass private variables as arguments either,
> even in call-by-value. I even went as far as creating the local variables x
> and y within the function, and assigning position.x, position.y to them, but
> still it did not work.

You really cannot use the object's private variables (this time the
location's "x" and "y" coordinates) outside the object's member
functions. This violates encapsulation. However, just like structure
variables, as long as the objects belong to the same class, you can
assign the state of one object to the other. Consider this code:

void ship::deployShip(location position){
     loc=position;
     ....
}


Thanks,
--
Mikhail


More information about the cs23021-2 mailing list