=========================preview======================
(COMP151)2005_s_comp151_by_eg_ckxab727.pdf
Back to COMP151 Login to download
======================================================
COMP 151: Object Oriented Programming
Spring Semester 2005
Final Examination
Saturday, 28 May 2005
4:30PM C 7:30PM

KEY
Name:
E-mail:
ID:
LAB:
Problem Points Score
1 FUNCTION POINTERS AND FUNCTION OBJECTS 10
2 OPERATOR OVERLOADING 10
3 ITERATORS AND STL ALGORITHMS 8
4 POLYMORPHISM 14
5 TEMPLATES AND INHERITANCE 18
6 INHERITANCE AND MEMBER CLASSES 9
7 MULTIPLE-CHOICE QUESTIONS 21
Total 90

1 Function Pointers and Function Objects (10 POINTS)
(a) [5 pts] Consider the following program:
#include <iostream>
using namespace std;

class Dog {
public:

int run(int i) const {
cout << "run:" << i << endl;
return i;

}

typedef int (Dog::*PMF)(int) const;

class FunctionObject {
Dog* ptr;
PMF pmem;

public:
FunctionObject() {
cout << "default constructor" << endl;
}

FunctionObject(Dog* wp, PMF pmf)
: ptr(wp), pmem(pmf) {
cout << "FunctionObject constructor" << endl;

}

int operator()(int i) const {
cout << "FunctionObject::operator()" << endl;
return (ptr->*pmem)(i); // Make the call

}
};

FunctionObject operator->*(PMF pmf) {
cout << "operator->*" << endl;
return FunctionObject(this, pmf);

}
};

int main() {
Dog w;
Dog::PMF pmf = &Dog::run;
cout << (w->*pmf)(1) << endl;
return 0;

}

Give the output of this program. Answer:
operator->*
FunctionObject constructor
FunctionObject::operator()
run:1
1

(b) [5 pts] Consider the following de.nition:
int (*pfunc)(float, char, int);

(1)
What does this de.nition mean?

Answer:
A type that is a pointer to a function with three parameters, float, char, intand returns an int.


(2)
What does it mean if the .rst pair of parentheses is omitted, that is


int *pfunc(float, char, int);

Does it have the same meaning as (1)? If not, what is the new meaning?

Answer:
It is not the same as (1). It now declares a function with three parameters, float, char, intand returns a pointer to int.


2 Operator Overloading (10 POINTS)
Consider the following program:
class Date
{
private:

int day;
int month;
int year;

public:
Date(int = 20, int = 5, int = 2005); // constructor
};

Date::Date(int dd, int mm, int yyyy)

{
day = dd;
month = mm;
year = yyyy;

}

(a) [4 pts] Overload the operator <<to display Dateobjects so the following works.
Date today(28, 5, 2005);
cout << today; // it prints "28-5-2005" on the screen

You have to declare the function inside the class but de.ne it outside.
Answer:
class Date
{
friend ostream& operator<<(ostream&, const Date&);
};

ostream& operator<<(ostream& out, const Date& d) {
return out << d.day << "-" << d.month << "-" << d.year;
};

(b) [6 pts] Overload the subscript operator []for the class Dateso that it returns the ith day after the current date. For example,
Date today(28, 5, 2005); // today is "28-5-2005"
Date tomorrow = today[1]; // the result is "29-5-2005"
Date future = today[100]; // the res