14.12. Multiple Choice ExercisesΒΆ

What is one use of data encapsulation?

Which of the following are accessor functions?

struct Student {
  private:
    int id;
  public:
    string name;
    int year;

    int getID () { return id; }
    int setID (int i) { id = i; }
    void printInfo () { cout << "Student: " << name << ", " << year; }
};

Which of the following are true?

What should replace the question marks in the code below? Use accessor functions.

class rightTriangle {
  int base;
  int height;

  public:
    int getBase () { return base; }
    int getHeight () { return height; }
    double calculateHypotenuse () {
      ???
    }
};

What is wrong with the code below?

class Plane {
  int flightNumber;
  string model;
  string origin;
  string destination;

  public:
    void printInfo () {
      cout << "Flight " << flightNumber << " (" << model
           << ") from " << origin << " to " << destination << endl;
    }
};

int main() {
  Plane p;
  p.flightNumber = 1846;
  p.model = "Boeing 787";
  p.origin = "Los Angeles";
  p.destination = "Detroit";
  p.printInfo ();
}

What is the output of the code below?

class Temp {
  private:
    double fahrenheit;
    double celsius;
    bool is_fahrenheit;
    bool is_celsius;

  public:
    double getFahrenheit () { return fahrenheit; }
    double getCelsius () { return celsius; }
    void setFahrenheit (double f) { fahrenheit = f; is_fahrenheit = true; is_celsius = false; }
    void setCelsius (double c) { celsius = c; is_celsius = true; is_fahrenheit = false; }
    void printTemp () {
      if (is_fahrenheit) {
        cout << "It is " << getFahrenheit() << " degrees Fahrenheit" << endl;
      }
      else {
        cout << "It is " << getCelsius() << " degrees Celsius" << endl;
      }
    }
};

int main() {
  Temp t;
  t.setFahrenheit (125);
  t.setCelsius (30);
  t.printTemp ();
}

Which of the following are true about invariants?

Take a look at the class definition of Date. What are some invariants we must maintain?

class Date {
  private:
    int day;
    int month;
    int year;
    bool is_birthday;
    string message;

  public:
    Date (int hour, int d, int m, int y, bool b, string m) {
      day = d;
      month = m;
      year = y;
      is_birthday = b;
      message = m;
    }
};

Take a look at the function below. What are its preconditions and postconditions?

int calculateRectangleArea (int length, int width) {
  return length * width;
}

What are private functions and what do they do?