14.12. Multiple Choice ExercisesΒΆ

What is one use of data encapsulation?

Which of the following are accessor functions?

struct student {
  private:
    int m_id;
  public:
    string name;
    int m_year;

    int id () { return m_id; }
    int id (int i) { m_id = i; }
    void print_info () { cout << "student: " << name << ", " << m_year; }
};

Which of the following are true?

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

class right_triangle {
  int m_base;
  int m_height;

  public:
    int base () { return m_base; }
    int height () { return m_height; }
    double calculate_hypotenuse () {
      ???
    }
};

What is wrong with the code below?

class plane {
  int flight_number;
  string model;
  string origin;
  string destination;

  public:
    void print_info () {
      cout << "Flight " << flight_number << " (" << model
           << ") from " << origin << " to " << destination << '\n';
    }
};

int main() {
  plane p;
  p.flight_number = 1846;
  p.model = "Boeing 787";
  p.origin = "Los Angeles";
  p.destination = "Detroit";
  p.print_info ();
}

What is the output of the code below?

class temp {
  private:
    double m_fahrenheit;
    double m_celsius;
    bool is_fahrenheit;
    bool is_celsius;

  public:
    double fahrenheit () { return m_fahrenheit; }
    double celsius () { return m_celsius; }
    void fahrenheit (double f) { m_fahrenheit = f; is_fahrenheit = true; is_celsius = false; }
    void celsius (double c) { m_celsius = c; is_celsius = true; is_fahrenheit = false; }
    void print_temp () {
      if (is_fahrenheit) {
        cout << "It is " << fahrenheit() << " degrees Fahrenheit" << '\n';
      }
      else {
        cout << "It is " << celsius() << " degrees Celsius" << '\n';
      }
    }
};

int main() {
  temp t;
  t.fahrenheit (125);
  t.celsius (30);
  t.print_temp ();
}

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 m_day;
    int m_month;
    int m_year;
    bool is_birthday;
    string message;

  public:
    date (int hour, int d, int m, int m_y, bool b, string m) {
      m_day = d;
      m_month = m;
      m_year = m_y;
      is_birthday = b;
      message = m;
    }
};

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

int calculate_rectangle_area (int m_length, int m_width) {
  return m_length * m_width;
}

What are private functions and what do they do?