If you have setters, you can check if the argument is valid. Although your observation is correct. Often getters setters are added for no reason at all.
Well this is the main idea behind encapsulation. Basically the data is hidden inside the object and can only be accessed by its public member functions. This is done so that data structures and operators are used as intended.
It tends to be more of a Java thing, than a C++ thing. But, I think it's important for what others have states. Allows to make sure the data is valid inside the class, rather than having to check it outside the class
Everything everyone has stated is true. However, making the member public is not the same thing as having a public interface to the private member (in some situations it is, depending on the members type).
consider this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Something
{
public:
void setTheThing(string thing);
string getTheThing();
private:
string theThing;
};
//in main...
{
Something mySomething;
mySomething.setTheThing("Mammoth");
string &myString = mySomething.getTheThing();//Makes a copy of the string
myString = "Tiger";
//.... myString now = tiger... mySomething.theThing is still "Mammoth"
}
Now consider using a public member in it's place...
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Something
{
public:
string theThing;
};
//in main...
{
Something mySomething;
mySomething.theThing = "Mammoth";
string &myString = mySomething.theThing; //References theThing's memory
myString = "Tiger";
//.... myString now = tiger... mySomething.theThing is now "Tiger" WHOOPS!
}
string &myString = mySomething.getTheThing(); does not compile
invalid initialization of non-const reference of type ‘std::string&’ from an rvalue of type ‘std::string'
However ¿what prevents me from using the setter and change its value?
Regarding encapsulation, getters/setters tend to drive the logic away from the class and increase coupling
By instance, instead of doing mario.hit(koopa); you end with something like
It compiles and gives the output I posted using VS2010 with platform toolset v100, obviously it might not be portable as you've stated. I was just showing the 'possible' pitfal that one might not think about.
However ¿what prevents me from using the setter and change its value?
That's my point, you would make a conscience decision to use the setting, but someone could unintentionally change it with my nonsense example.