CS 70

Exercise: const Member Functions

Consider this class:

class Sheep {
 public:
    Sheep();

    void bleet(int numBahs, int numAsPerBah);

    float getWoolLength();

    void growWool();
    void shear();

 private:
    float woolLength_;
};
Sheep::Sheep() : woolLength_{0} {
    // Nothing (else) to do.
}

void Sheep::bleet(int numBahs, int numAsPerBah) {
    for (int i = 0; i < numBahs; ++i) {
        cout << "B";
        for (int j = 0; j < numAsPerBah; ++j) {
            cout << "a";
        }
        cout << "h! ";
    }
    cout << endl;
}

float Sheep::getWoolLength() {
    return woolLength_;
}

void Sheep::growWool() {
    woolLength_ = woolLength_ + (10.0 - woolLength_)/20.0;
}

void Sheep::shear() {
    woolLength_ = 0;
}

Which member functions should be declared const?

Assume that bleet and getWoolLength are const and consider this code snippet:

1| Sheep fluffy{};
2| const Sheep daffodil{};
3| float totalWool = fluffy.getWoolLength() + daffodil.getWoolLength();
4| fluffy.growWool();
5| daffodil.sheer();
6| float newTotalWool = fluffy.getWoolLength() + daffodil.getWoolLength();

Which line of code would cause a compiler error? (Just the line number.)

(When logged in, completion status appears here.)