In general it is better practice to make class data members private and only all
ID: 3731718 • Letter: I
Question
In general it is better practice to make class data members private and only allow the user of the class to access them through setter and getter methods. We do this so that we can have more control over what values attributes are set to.
Someone might accidentally do something like this:
Robot bb8 = Robot(0, 0, 'N');
bb8.heading = '?';
By only allowing the heading attribute to be changed via the setter, for example, we could ensure that heading is always 'N', 'S', 'E' or 'W'.
Robot bb8 = Robot(0, 0, 'N');
bb8.setHeading('?');
For this question, change the x, y, and heading attributes so that they have the private modifier.
Then, create the getter and setter methods for the Robot class. In particular, write methods to get and set the values of the x, y, and heading attributes.
Name your functions the following:
getX
getY
getHeading
setX
setY
setHeading
The getters should return the corresponding attribute, and the setters should take in a value and set the attribute accordingly. (e.g., getX should return the x value for the robot, setX should take in an integer and set the x value to that integer) (in c++)
Code from the previous question:
class Robot {
//declaring the variables
public:
int x;
int y;
char heading;
public: //constructor
Robot(int start_x,int start_y,char start_heading){
x=start_x;
y=start_y;
heading=start_heading;
}
};
Explanation / Answer
class Robot
{
int x;
int y;
char heading;
public:
// constructor
Robot( int x, int y, char heading )
{
this->x = x;
this->y = y;
this->heading = heading;
}
// getter methods
int getX()
{
return this->x;
}
int getY()
{
return this->y;
}
char getHeading()
{
return this->heading;
}
// setter method
void setX(int x)
{
this->x = x;
}
void setY(int y)
{
this->y = y;
}
void setHeading(char heading)
{
this->heading = heading;
}
};