Access Control
You've heard about public and private access before, right?
Yup. Public members can be accessed by any piece of code. Private members can only be accessed by code within the class itself.
Great! It's the same here. The syntax is a little bit different than in Java, but it's pretty straightforward. Check out the highlights in
cow.hpp
below.
cow.hpp
:
...
class Cow {
public:
// We can only have a Cow if we know
// how many spots it has and how old it is
Cow(int numSpots, int age);
Cow() = delete;
// Moo the right number of times.
void moo(int numMoos) const;
// Accessor member functions
int getNumSpots() const;
int getAge() const;
// Mutator member functions
void setNumSpots(int numSpots);
void setAge(int age);
private:
// Per-Cow data
int numSpots_;
int age_;
};
...
Notice (below) that
public
andprivate
are not mentioned at all incow.cpp
.Access levels are part of the class definition, not part of a function header.
cow.cpp
:
...
Cow::Cow(int numSpots, int age)
: numSpots_{numSpots},
age_{age}
{
cout << "Made a cow with " << numSpots_ << " spots!" << endl;
}
void Cow::moo(int numMoos) const {
for (int i = 0; i < numMoos; ++i) {
cout << "Moo! ";
}
cout << endl;
}
int Cow::getNumSpots() const {
return numSpots_;
}
int Cow::getAge() const {
return age_;
}
void Cow::setNumSpots(int numSpots) {
numSpots_ = numSpots;
}
void Cow::setAge(int age) {
age_ = age;
}
So, can one
Cow
object access the private member variables of anotherCow
object?Yes! Privacy applies at the class level so all objects of the same class can access each other's private members.
(When logged in, completion status appears here.)