Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access private variables using public functions? [closed]

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?

like image 568
Jim Jam Avatar asked Dec 12 '13 18:12

Jim Jam


People also ask

Can public functions access private variables?

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?

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.

How do you access a private variable outside the function in Python?

However, you can access private variables and the private method from outside the class. Use the syntax like instance _class-name__private-attribute .


1 Answers

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).

like image 135
SJuan76 Avatar answered Oct 13 '22 01:10

SJuan76