Private variables are there to help with the work behind the scenes in a class, work that the creator doesn’t want you interfering in. Just because you can’t see or access the private variables, it doesn’t mean the compiler’s just going to throw them away. Perhaps it will make more sense to you in this example:
class Animal {
int legs;
public:
Animal(int legs) : legs(legs) {}
~Animal() {}
std::string how_fast() {
if(legs > 4) {
return "Super fast!";
} else if (legs > 2) {
return "Pretty fast.";
} else {
return "Slow.";
}
}
};
class Lion: public Animal{
int humans_eaten;
public:
Lion(int eaten) : Animal(4), humans_eaten(eaten) {}
~Lion() {}
};
Here legs
is private in the Animal
class because this should already be known to the children. If I am doing calculations in Lion
that require me to use the number of legs, it will always be 4, however, this is not always the case for Animal
.
Even though Lion can never access Animal’s legs
, Animal needs to know that number for its calculations in how_fast
. Does this make sense?
solved What actually happenes in this code?