CS 70

Access Control

  • LHS Cow speaking

    You've heard about public and private access before, right?

  • Cat speaking

    Yup. Public members can be accessed by any piece of code. Private members can only be accessed by code within the class itself.

  • LHS Cow speaking

    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_;
};
...
  • RHS Cow speaking

    Notice (below) that public and private are not mentioned at all in cow.cpp.

  • LHS Cow speaking

    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;
}

Where do you put public: and private: for a class definition?

  • Duck speaking

    So, can one Cow object access the private member variables of another Cow object?

  • LHS Cow speaking

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