So I don't know if you any of you have been/goes on the NewBoston.Com (great resource by the way), but I was watching this video and the teacher was saying how you can access private info using public functions...
This is the video: http://www.youtube.com/watch?v=jTS7JTud1qQ
And of course, just skip to the end to get to the gist of it.
The thing I don't get though, is how can you access private information using a public function. If you make a function that's public that allows anyone to set the name, and get that name, then isn't it just public anyway?, Wouldn't anyone be able to mess my code and my desired output?
Only the member functions or the friend functions are allowed to access the private data members of the class.
How can a private variable be accessed? Use the property for that variable., Use a method that is in the same class as the private variable, which can access the variable.) A class diagram helps you design a class, so it is required to show every implementation detail.
However, you can access private variables and the private method from outside the class. Use the syntax like instance _class-name__private-attribute .
The point of providing a public method to change a private variable is that you can add additional controls.
There is not a lot of difference between
class A {
public:
int age;
}
and
class B {
private:
int age;
public:
void setAge(int _age);
}
B::setAge(int _age) {
this->age = _age;
}
But, in the second case, you can add logic that rejects some data (v.g. a negative value) or updates other fields. So you can ensure that the data of your object will remain consistent. If you follow the first approach, that logic should replicated every time the property is accessed directly (note: many programmers will forget to do so).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With