Course Materials

OOP - Week 3: 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 Question 1, write the whole program in one file. In Question 2, write three files.

Filter:
Sort:

Question 1

Write a complete class Date with the following:

  1. Three private data members, day, month and year, all int.
  2. A setter and a getter for each member. A setter ignores an invalid value: a day must be from 1 to 31, a month from 1 to 12, and a year must be at least 1.
  3. One constructor with default parameters, day = 1, month = 1 and year = 2000. It uses the setters, so an invalid value is ignored and that member keeps its safe starting value.
  4. A function print() that prints the date.
  5. A function isEqual(other) that takes another Date and returns true if both dates have the same day, month and year.
  6. A function later(other) that takes another Date and returns the later of the two dates as a new Date. If the dates are equal, return either one.
  7. A function addMonths(months) with the default value 1. It returns a new Date that is that many months later. The day stays the same, and the year goes up when the month passes 12. The date it was called on is not changed.
  8. A function monthsBetween(other) that returns the number of months between the two dates as a positive number. Ignore the days.

Pass the other date by const reference, and read its data members directly.

In main:

  • Create d1, d2, d3 and d4. d1 and d2 have the same values, d3 has different values, and d4 has no arguments. Print all four.
  • Print d1.isEqual(d2) and d1.isEqual(d3).
  • Call print() on d1.later(d3).
  • Create d5 with d1.addMonths() and d6 with d1.addMonths(n), where n is a number of your choice that puts d6 in the next year. Print d1, d5 and d6.
  • Print d1.monthsBetween(d3) and d3.monthsBetween(d1).
Solution
#include <iostream>
using namespace std;

class Date {
private:
    int day, month, year;

public:
    Date(int d = 1, int m = 1, int y = 2000) {  // default parameters
        day = 1;                                // safe values first
        month = 1;
        year = 2000;
        setDay(d);
        setMonth(m);
        setYear(y);
    }

    void setDay(int d) {
        if (d >= 1 && d <= 31)
            day = d;
    }
    void setMonth(int m) {
        if (m >= 1 && m <= 12)
            month = m;
    }
    void setYear(int y) {
        if (y >= 1)
            year = y;
    }

    int getDay() {
        return day;
    }
    int getMonth() {
        return month;
    }
    int getYear() {
        return year;
    }

    void print() {
        cout << day << "/" << month << "/" << year << endl;
    }

    bool isEqual(const Date& other) {
        return day == other.day && month == other.month && year == other.year;
    }

    Date later(const Date& other) {             // returns the later of the two dates
        bool mine;                              // true when this date is the later one
        if (year != other.year)
            mine = year > other.year;
        else if (month != other.month)
            mine = month > other.month;
        else
            mine = day >= other.day;

        if (mine)
            return Date(day, month, year);
        return other;                           // a copy of the other date
    }

    Date addMonths(int months = 1) {            // returns a new date, this date is not changed
        int total = year * 12 + (month - 1) + months;
        return Date(day, total % 12 + 1, total / 12);
    }

    int monthsBetween(const Date& other) {
        int a = year * 12 + month;
        int b = other.year * 12 + other.month;
        return a > b ? a - b : b - a;
    }
};

int main() {
    Date d1(15, 11, 2025);
    Date d2(15, 11, 2025);                      // the same values as d1
    Date d3(3, 2, 2026);                        // different values
    Date d4;                                    // no arguments

    d1.print();
    d2.print();
    d3.print();
    d4.print();

    cout << d1.isEqual(d2) << endl;             // 1
    cout << d1.isEqual(d3) << endl;             // 0

    d1.later(d3).print();

    Date d5 = d1.addMonths();                   // one month later
    Date d6 = d1.addMonths(3);                  // 3 months later: the next year
    d1.print();                                 // d1 is not changed
    d5.print();
    d6.print();

    cout << d1.monthsBetween(d3) << endl;
    cout << d3.monthsBetween(d1) << endl;

    return 0;
}

                    

Question 2

Write the class Employee in two files, and use it in a third file. Put the default values in the header only.

Employee.h (with a header guard) and Employee.cpp:

  • Private data members: id (int) and salary (double).
  • A constructor with default parameters (id = 0, salary = 0.0) that uses the setters.
  • Setters and getters, named setId, setSalary, getId and getSalary. setId accepts only a positive value, and setSalary accepts only zero or more.
  • raise(percent) increases the salary by that percent. percent is a double, and its default is 10.
  • earnsMore(other) returns true if this salary is higher than the salary of other.
  • print() prints the id and the salary.

main.cpp has these functions. Each one receives the array and its size:

  • totalSalary returns the sum of the salaries as a double.
  • findById(arr, size, id) returns the index of that id, or -1 if it is not found.
  • raiseAll(arr, size, percent) raises every employee. The default percent is 10.
  • printAll prints every employee.

In main:

  • Create staff, an array of 5 employees. Give the first three an id and a salary with constructor calls, and leave the last two to the constructor’s default values.
  • Use the setters on staff[3] (a valid id and a valid salary) and on staff[4] (a valid id and a negative salary).
  • Print all the employees.
  • Print staff[0].earnsMore(staff[1]), the total salary, and findById for an id that exists and for one that does not.
  • Call staff[1].raise() with no argument and print staff[1]. Then call raiseAll with a percent of your choice, and print the total salary.
Solution
Employee in three filescode/oop/week-03/worksheet/solution-02
#ifndef EMPLOYEE_H
#define EMPLOYEE_H

class Employee {
private:
    int id;
    double salary;

public:
    Employee(int i = 0, double s = 0.0);

    void setId(int i);
    void setSalary(double s);

    int getId();
    double getSalary();

    void raise(double percent = 10);
    bool earnsMore(const Employee& other);
    void print();
};

#endif
#include <iostream>
#include "Employee.h"
using namespace std;

Employee::Employee(int i, double s) {
    id = 0;
    salary = 0.0;
    setId(i);
    setSalary(s);
}

void Employee::setId(int i) {
    if (i > 0)
        id = i;
}

void Employee::setSalary(double s) {
    if (s >= 0)
        salary = s;
}

int Employee::getId() {
    return id;
}

double Employee::getSalary() {
    return salary;
}

void Employee::raise(double percent) {
    setSalary(salary + salary * percent / 100);
}

bool Employee::earnsMore(const Employee& other) {
    return salary > other.salary;
}

void Employee::print() {
    cout << "id " << id << ", salary " << salary << endl;
}
#include <iostream>
#include "Employee.h"
using namespace std;

double totalSalary(Employee arr[], int size) {
    double sum = 0;
    for (int i = 0; i < size; i++)
        sum += arr[i].getSalary();
    return sum;
}

int findById(Employee arr[], int size, int id) {
    for (int i = 0; i < size; i++) {
        if (arr[i].getId() == id)
            return i;
    }
    return -1;
}

void raiseAll(Employee arr[], int size, double percent = 10) {
    for (int i = 0; i < size; i++)
        arr[i].raise(percent);
}

void printAll(Employee arr[], int size) {
    for (int i = 0; i < size; i++)
        arr[i].print();
}

int main() {
    Employee staff[5] = { Employee(101, 1200), Employee(102, 900), Employee(103, 1500) };
    staff[3].setId(104);
    staff[3].setSalary(1100);
    staff[4].setId(105);
    staff[4].setSalary(-50);

    printAll(staff, 5);

    cout << "staff[0] earns more than staff[1]: " << (staff[0].earnsMore(staff[1]) ? "yes" : "no") << endl;
    cout << "total: " << totalSalary(staff, 5) << endl;
    cout << "index of id 103: " << findById(staff, 5, 103) << endl;
    cout << "index of id 999: " << findById(staff, 5, 999) << endl;

    staff[1].raise();
    cout << "after staff[1].raise(): ";
    staff[1].print();

    raiseAll(staff, 5, 50);
    cout << "total after raiseAll 50: " << totalSalary(staff, 5) << endl;

    return 0;
}

Question 3

Trace the following program. The class Coin has a constructor with a default parameter, written with a member initializer list, and a copy constructor. Every constructor and the destructor print a message. Assume that the compiler never makes an extra copy of a temporary object: not when it creates the array elements, not when twice returns, and not when the result initializes c. The only copy is the one made by passing an object by value.

#include <iostream>
using namespace std;

class Coin {
private:
    int value;

public:
    Coin(int v = 1) : value(v) {
        cout << "make " << value << endl;
    }
    Coin(const Coin& other) : value(other.value) {
        cout << "copy " << value << endl;
    }
    ~Coin() {
        cout << "free " << value << endl;
    }

    int getValue() {
        return value;
    }
    bool isBigger(const Coin& other) {
        return value > other.value;
    }
    Coin twice() {
        return Coin(value * 2);
    }
};

void byValue(Coin c) {
    cout << "byValue " << c.getValue() << endl;
}

void byRef(Coin& c) {
    cout << "byRef " << c.getValue() << endl;
}

int main() {
    Coin a(5);
    Coin b;
    Coin wallet[3] = { Coin(10), Coin(20) };
    byValue(a);
    byRef(b);
    if (b.isBigger(a))
        cout << "b is bigger" << endl;
    else
        cout << "b is not bigger" << endl;
    Coin c = a.twice();
    cout << "end" << endl;
    return 0;
}

Write the exact output of the program. Do not run it before you have written your answer.

Solution
make 5
make 1
make 10
make 20
make 1
copy 5
byValue 5
free 5
byRef 1
b is not bigger
make 10
end
free 10
free 1
free 20
free 10
free 1
free 5