I'm very new to C++ and object-oriented programming in general. I'm trying to wrap my hand around classes, and accessors (getters and setters).
Say I have the class Person
. Its nothing too important, it just stores a person's name and HP. The name is a string, and the HP is an integer. I already know that it is incredibly stupid to leave both these variables in the public access specifier, so I would leave both the name and the HP in the private access specifier instead. I understand that I can use a constructor to set the variables when first creating an instance of the object, but things like HP have to be consistently updated...
Which brings in the concept of getters and setters.
By using public getter and setter functions, I would be able to change the HP of the Person object. This however, would result in the breaking of encapsulation, which no one wants.
I understand that getters can be mandatory in C++ in some occasions, but are there any alternatives to setters? Thanks.
BTW, here's some code that shows what I've been trying to show...
#include <string>
using namespace std;
class Person {
public:
Person(string setName, int setHp) {
setName = name;
setHp = hp;
}
int getHP() {
return hp;
void setHP(int hpSet) {
hp = hpSet
}
private:
string name;
int hp;
}
int main() {
Person guy("Mark", "100");
// Say Mark here was attacked or something... his HP would go down...
guy.setHP(75);
return 0;
}