Originally Posted by
liquidxit2
Private member variables are used for data that should only be accessed by member functions and not from outside code e.g. int main() code or other classes(unless said class is inherited). Basically to allow class calculations to be pure in a sense.
This is wrong. inherited classes cannot access the private member variables of their base class.
variables are made private to encapsulate the class. For instance, let's say you have the following class:
Code:
class Person
{
public:
int age;
string name;
};
The problem is that a user could do something like:
Code:
Person p;
p.age = -1; // Uh oh, this isn't good!
We can fix the above code by doing something like:
Code:
class Person
{
public:
void SetAge(int new_age)
{
if(new_age < 0)
{
cout << "ERROR: Invalid age being set. Using zero instead\n";
age = 0;
}
else
age = new_age;
}
int GetAge() { return age; }
private:
int age;
string name;
};
The above code doesn't give the user direct access to the member variables. This means that you can do things like validate input.