Course Materials

OOP - Week 2: Programming Questions

Note: Try to solve these questions on your own before checking the solutions. If you are stuck, reread Lecture 1, Lecture 2 and Lecture 3. In Questions 1 and 2, write the whole program in one file and compare your output with the solution.

Filter:
Sort:

Question 1

Write a complete class Rectangle with the following:

  1. Two private data members, width and height, both int.
  2. A setter and a getter for each member. A setter ignores a value that is zero or negative.
  3. A default constructor that sets both members to 1 and prints default constructor.
  4. A parameterized constructor (width and height) that uses the setters, so an invalid value is ignored and that member stays 1. It prints constructor WxH after the setters have run, so the numbers are the stored ones.
  5. A copy constructor that prints copy constructor WxH.
  6. A destructor that prints destructor WxH.
  7. Member functions area(), perimeter() and print(). The function print() prints WxH area A perimeter P.

In main:

  • Create r1 with the default constructor, r2 with a width and a height of your choice, r3 as a copy of r2, and r4 with an invalid width and a valid height.
  • Set a new width and height for r1, and change the height of r3.
  • Print the four rectangles with print().
  • Then print r2 is W wide and H high using the getters of r2.

Run your program and look at the output: why is r2 unchanged after you changed the height of r3? In which order are the destructors called, and why?

Solution
#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;

public:
    Rectangle() {                           // default constructor
        width = 1;
        height = 1;
        cout << "default constructor" << endl;
    }
    Rectangle(int w, int h) {               // parameterized constructor
        width = 1;                          // safe values first
        height = 1;
        setWidth(w);
        setHeight(h);
        cout << "constructor " << width << "x" << height << endl;
    }
    Rectangle(const Rectangle& other) {     // copy constructor
        width = other.width;
        height = other.height;
        cout << "copy constructor " << width << "x" << height << endl;
    }
    ~Rectangle() {                          // destructor
        cout << "destructor " << width << "x" << height << endl;
    }

    void setWidth(int w) {
        if (w > 0)
            width = w;
    }
    void setHeight(int h) {
        if (h > 0)
            height = h;
    }
    int getWidth() {
        return width;
    }
    int getHeight() {
        return height;
    }

    int area() {
        return width * height;
    }
    int perimeter() {
        return 2 * (width + height);
    }
    void print() {
        cout << width << "x" << height << " area " << area() << " perimeter " << perimeter() << endl;
    }
};

int main() {
    Rectangle r1;
    Rectangle r2(4, 5);
    Rectangle r3 = r2;
    Rectangle r4(-3, 7);        // the width is invalid

    r1.setWidth(6);
    r1.setHeight(2);
    r3.setHeight(10);

    r1.print();
    r2.print();
    r3.print();
    r4.print();
    cout << "r2 is " << r2.getWidth() << " wide and " << r2.getHeight() << " high" << endl;

    return 0;
}

                    

Question 2

Every student has exactly 5 subjects. Declare const int SUBJECTS = 5; before the class and use it everywhere instead of the number 5.

Write a complete class Student with the following:

  1. Two private data members: id (int) and an array grades of SUBJECTS integers.
  2. A setter setId, which accepts only a positive value, and a setter setGrade(subject, grade), which accepts only a subject from 0 to 4 and a grade from 0 to 100. A setter ignores an invalid value.
  3. A second setter setGrades(marks, count) that receives an array of grades and its size. It sets the subjects one by one by calling setGrade, so every grade is checked, and it never goes past the 5 subjects.
  4. The getters getId() and getGrade(subject). Make getGrade return -1 for an invalid subject.
  5. One constructor with default parameters, id = 1 and grade = 0. It gives the student that id, sets all five grades to the given grade using the setters, and prints constructor ID. It must work with no arguments, with one argument, and with two arguments.
  6. A copy constructor that copies the id and every element of the array, and prints copy constructor ID. A destructor that prints destructor ID.
  7. A function average() that returns the average of the five grades as a double (use a cast to double, as you did in Week 1, so the division is not an integer division), a function lowest() that returns the lowest grade, and a function highest() that returns the highest grade.
  8. A function print() that prints id I, grades G G G G G, average A, lowest L, highest H. Print the average with a plain cout, without setprecision.

In main:

  • Create s1 with no arguments, s2 and s3 with an id and a grade of your choice, s4 as a copy of s3, and s5 with only an id (one argument).
  • Set a grade in two subjects of s1.
  • Try s2.setGrade with an invalid subject.
  • Create an array of five grades where one grade is above 100, and give it to s2 with setGrades.
  • Set a grade in the last subject of s3. Change the id of s4, and change its grade in subject 0.
  • Print the first four students with print().
  • Print the last grade of s3 using getGrade. Print the id of s5 and its grade in a subject that does not exist, using getId and getGrade.

Run your program and look at the output: why does s2 keep its old grade in the position of the invalid grade after setGrades? And you changed the last grade of s3 after s4 was copied from it, so why does s4 still have the old grade?

Solution
#include <iostream>
using namespace std;

const int SUBJECTS = 5;                     // every student has exactly 5 subjects

class Student {
private:
    int id;
    int grades[SUBJECTS];

public:
    Student(int i = 1, int g = 0) {         // default parameters
        id = 1;                             // safe value first
        setId(i);
        for (int s = 0; s < SUBJECTS; s++) {
            grades[s] = 0;                  // safe values first
            setGrade(s, g);                 // the setter checks the grade
        }
        cout << "constructor " << id << endl;
    }
    Student(const Student& other) {         // copy constructor
        id = other.id;
        for (int s = 0; s < SUBJECTS; s++)
            grades[s] = other.grades[s];    // copy every element of the array
        cout << "copy constructor " << id << endl;
    }
    ~Student() {                            // destructor
        cout << "destructor " << id << endl;
    }

    void setId(int i) {
        if (i > 0)
            id = i;
    }
    void setGrade(int subject, int grade) {
        if (subject < 0 || subject >= SUBJECTS)     // invalid subject
            return;
        if (grade < 0 || grade > 100)               // invalid grade
            return;
        grades[subject] = grade;
    }
    void setGrades(const int g[], int count) {      // an array of grades and its size
        for (int s = 0; s < count && s < SUBJECTS; s++)
            setGrade(s, g[s]);                      // every grade is checked by setGrade
    }
    int getId() {
        return id;
    }
    int getGrade(int subject) {
        if (subject < 0 || subject >= SUBJECTS)
            return -1;
        return grades[subject];
    }

    double average() {
        int sum = 0;
        for (int s = 0; s < SUBJECTS; s++)
            sum += grades[s];
        return (double)sum / SUBJECTS;
    }
    int highest() {
        int best = grades[0];
        for (int s = 1; s < SUBJECTS; s++) {
            if (grades[s] > best)
                best = grades[s];
        }
        return best;
    }
    int lowest() {
        int worst = grades[0];
        for (int s = 1; s < SUBJECTS; s++) {
            if (grades[s] < worst)
                worst = grades[s];
        }
        return worst;
    }
    void print() {
        cout << "id " << id << ", grades";
        for (int s = 0; s < SUBJECTS; s++)
            cout << " " << grades[s];
        cout << ", average " << average() << ", lowest " << lowest() << ", highest " << highest() << endl;
    }
};

int main() {
    Student s1;
    Student s2(2023, 60);
    Student s3(2024, 90);
    Student s4 = s3;
    Student s5(7);              // only the id is given

    s1.setGrade(0, 75);
    s1.setGrade(1, 82);
    s2.setGrade(5, 90);         // invalid subject, ignored

    int marks[SUBJECTS] = {88, 92, 150, 65, 100};   // 150 is not a valid grade
    s2.setGrades(marks, SUBJECTS);

    s3.setGrade(4, 70);
    s4.setId(2025);
    s4.setGrade(0, 50);

    s1.print();
    s2.print();
    s3.print();
    s4.print();
    cout << "s3, subject 4: " << s3.getGrade(4) << endl;
    cout << "s5, id " << s5.getId() << ", subject 9: " << s5.getGrade(9) << endl;

    return 0;
}

                    

Question 3

Trace the following program. It uses two classes: Box has a default constructor, a parameterized constructor and a copy constructor, and Tag has one constructor with default parameters, written with a member initializer list, and a copy constructor. Every constructor and destructor prints a message.

#include <iostream>
using namespace std;

class Box {
private:
    int size;

public:
    Box() {
        size = 1;
        cout << "Box default" << endl;
    }
    Box(int s) {
        size = s;
        cout << "Box param " << size << endl;
    }
    Box(const Box& other) {
        size = other.size;
        cout << "Box copy " << size << endl;
    }
    ~Box() {
        cout << "Box destroy " << size << endl;
    }
    int getSize() {
        return size;
    }
};

class Tag {
private:
    int id, level;

public:
    Tag(int i = 0, int l = 5) : id(i), level(l) {
        cout << "Tag " << id << "," << level << endl;
    }
    Tag(const Tag& other) : id(other.id), level(other.level) {
        cout << "Tag copy " << id << endl;
    }
    ~Tag() {
        cout << "Tag destroy " << id << endl;
    }
};

void take(Box b) {
    cout << "take " << b.getSize() << endl;
}

void look(Box& b) {
    cout << "look " << b.getSize() << endl;
}

int main() {
    Box a;
    Box b(7);
    Box c = b;
    Tag t1;
    Tag t2(3);
    Tag t3(4, 9);
    Tag t4 = t3;
    take(b);
    look(c);
    cout << "end" << endl;
    return 0;
}
  1. Write the exact output of the program. Do not run it before you have written your answer.
Solution
Box default
Box param 7
Box copy 7
Tag 0,5
Tag 3,5
Tag 4,9
Tag copy 4
Box copy 7
take 7
Box destroy 7
look 7
end
Tag destroy 4
Tag destroy 4
Tag destroy 3
Tag destroy 0
Box destroy 7
Box destroy 7
Box destroy 1

                    
  1. For every statement in main that creates an object or calls a function with an object, choose the constructor that runs.
Which constructor runs? 0 / 9 answered

This question needs JavaScript to check your answers. You can still read the program and work out the answers on paper.

1.Box a;line 54 of the program
Answer for Box a;
2.Box b(7);line 55 of the program
Answer for Box b(7);
3.Box c = b;line 56 of the program
Answer for Box c = b;
4.Tag t1;line 57 of the program
Answer for Tag t1;
5.Tag t2(3);line 58 of the program
Answer for Tag t2(3);
6.Tag t3(4, 9);line 59 of the program
Answer for Tag t3(4, 9);
7.Tag t4 = t3;line 60 of the program
Answer for Tag t4 = t3;
8.take(b);line 61 of the program
Answer for take(b);
9.look(c);line 62 of the program
Answer for look(c);