2.4. Exercises#

Many of these exercises are taken from past exams of ECE 244 Programming Fundamentals courses at University of Toronto. The solutions are provided in the answer boxes.

Headings in this page classify the exercises into different categories: [Easy], [Intermediate], and [Challenging]. I suggest you start by easy exercises and work your way up to the challenging ones.

Question 7 in Fall 2021 Midterm Exam [Easy]

Consider the class definition shown below. Assume that iostream and string are included, and that the std namespace is used. Also assume that the class is correctly implemented.

class Book {
 public:
  Book() { cout << "A new book is added." << endl; }
  Book(string s) {
    cout << "Book " << s << " is added." << endl;
    name = s;
  }
  ~Book() { cout << "Book " << name << " is removed." << endl; }

 private:
  string name = "ECE244";
};

What is the output of the following main function?

Book* b1;

int main() {
  Book b2;
  Book* b3 = new Book("Pride and Prejudice");

  if (true) {
    b1 = new Book();
    Book b4("Wuthering heights");
    delete b3;
    Book* b5 = new Book[2];
  }

  delete b1;
  return 0;
}

Question 1 in Fall 2022 Midterm Exam [Easy]

Consider the following C++ program. There are three statements in the main function: A, B, and C. Which of these three statements will trigger compile-time errors?

class ECE244 {
 private:
  int num_student;
  int num_TA;
  int get_num_instructor();

 public:
  int num_instructor;
  int get_num_student();
  int get_num_TA();
};

int main() {
  ECE244 year2022;
  int num_student = year2022.num_student;              // Statement A
  int num_TA = year2022.get_num_TA();                  // Statement B
  int num_instructor = year2022.get_num_instructor();  // Statement C
  return 0;
}

Modified Question 9 in Fall 2018 Midterm Exam [Challenging]

Consider the following definition/implementation of a class called Shape that appears in the file: Shape.h.

Shape.h

#include <iostream>
using namespace std;
class Shape {
 private:
  int ID;

 public:
  Shape() {
    ID = 0;
    cout << "Constructor 1 " << ID << endl;
  }
  Shape(int id) {
    ID = id;
    cout << "Constructor 2 " << ID << endl;
  }

  ~Shape() { cout << "Destructor " << endl; }

  int getID() const { return ID; }
  void setID(int id) { ID = id; }
};

The following is a main program that uses the above class.

main.cpp

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

int getShapeID(Shape& s) {
  return s.getID();
}
int main() {
  Shape circle(5);
  Shape line2[2];

  cout << circle.getID() << endl;
  cout << getShapeID(line2[1]) << endl;
  return 0;
}

What is the output of the program? Select one of the answers from the table below.