Você está na página 1de 11

1

CS2620 Review Topics for Midterm


1. Identifying classes and objects from problem description. C++ class definition
syntax. see class notes, Section 6.2 and 6.3 of the text book)
2. Purpose and syntax for const and static methods and data members. Scope of a
class member. Different type of class constructors. (see class notes, Section 6.3
of the text book)
3. Function overloading, default arguments (pages 157-162, 288-289 of the text
book and class notes), default constructors, copy constructors, type conversion
constructors and explicit declaration (pages 157-162, 288-289 of the text book
and class notes)
4. Overloaded operator function definition and implementation, friend functions
and their proper use, reference return from a function and call cascading (Chapter
8 and class notes)
5. Storage classes: characteristics of local static, global, stack, and heap memory,
pointer variable declaration, de-referencing pointers, pointer arithmetic, dynamic
memory allocation and deallocation, constant pointers and pointer to constants,
pointer parameters, pointers and arrays, pointer arithmetic (Chapter 12 and class
notes)

Sample problems for Midterm

Below are sample problems for the midterm test. Although these problems are similar
to the type of problems you can expect on the test, please be advised that the test is not
limited to the type of problems listed here.
1. Which of the following vector definitions are in error?
(a) vector< vector <int> > ivec;
(b) vector< int > ivec2 = {0, 1, 2, 3};
2. Given a class named Person with the following two data members
string name;
string address;
and the following member functions
Person( const string &n, const string &a) {
name = n); address = a;
}
string get_name() const{ return name;);
string get_address() const {return address);

which members would you declare in public and which members would you
declare in private sections of the class? Explain your choice.
3. A Clock object has three attributes: hour, minute, and second. The following
design requirements are presented to you
Constructor(s) are required to create clock objects with user-specified values for hour, minute, and second. In addition, a default constructor is
needed as in the following code example:
Clock c1; // use default values to construct c1 Clock
Clock c2(19,25,10); // c2 is created with
// hour = 19, minute = 25, second = 10
Set an existing Clock object to a new value
c1.setClock(8, 30, 0); // set c1 to: hour = 8, minute = 30 ,second = 0
Obtain data member values
c2.getHour(); // returns hour
c2.getMinute(); // returns minute
c2.getSecond(); // returns second
Simulate a clock tick (advance the clock by one second)
c2.tick(); // c2 is incremented by one second
Print the time
c1.display(); //

outputs 08:30:00

(a) Give a complete definition of the Clock class as per specification given
above.
(b) Implement the display() setClock(), and tick() member functions.
(c) Overload the stream insertion and extraction operators for Clock class.
4. Circle the correct answer
(a) By default, the C++ language makes
in the default assignment operator.
a) a memberwise copy of all the data members
b) a deep copy of all the data
c) neither, it will not compile because you need to provide the assignment
operator
d) none of the above
(b) In C++, the same name can be associated with multiple definitions. The
compiler selects the appropriate definition by:
a) looking at the function signature
b) looking at the definitions that were defined in the same scope
c) looking at the return type
d) all of the above
2

(c) You would declare an operator as friend only if:


a) it has less than three arguments
b) it used dynamic memory
c) it returned a reference parameter
d) none of the above
(d) Passing a parameter that avoids the creation of a copy of the argument while
at the same time not allowing the actual argument to be modified is:
a) a const reference parameter
b) a reference parameter
c) a parameter passed by value
d) a temporary object
5. Consider the following code:
class Value {
private:
int x;
public:
Value(int i = 0) : x(i) {}
Value(const Value& v) { x = v.x; }
Value operator/(int d) {
return Value(x / d);
}
};
bool Value::operator==(const Value& Other) {
return (this == &Other);
}
int main() {
Value x(5), z(5);
if (x == x)
cout << True-;
else
cout << False-;
if (x == z)
cout << True << endl;
else
cout << False << endl;
return 0; }

(a) What does the above main program print?


(b) With the following different main program, but using the Value class from
above, answer the following questions:

int main() {
Value m(5); Value z(m);
if (m == m)
cout << True-;
else
cout << False-;
if (m == z)
cout << True << endl;
else
cout << False << endl;
return 0;
}
i. The line Value z(m) in the second main program above calls the:
a) default constructor
b) copy constructor
c) default constructor followed by the copy constructor
d) default constructor followed by the assignment operator
ii. With this new main program, the program now prints:
a) True-True
b) True-False
c) False-True
d) False-False
6. Why do you think the built-in array does not support the assignment of one array
to another? What information is required to support this operation?
Solution: The name of a built-in array, when appears in an expression, is implicitly converted to a const pointer, and it points to the first element in the
array. Since a const object cannot be assigned to after its initialization, we
may not assign one array with another.
The language was not designed to handle array assignments. The compiler
would have to know the length of the arrays at run-time, to generate code
to support assignment of one array with another.
7. Explain the difference between the four objects defined below
(a) int ival = 1024;
(b) int *pi = &ival;
(c) int *pi2 = new int(1024);
(d) int *pi3 = new int[1024];
Solution:
(a) The declaration instructs the compiler to allocate sufficient storage
to hold a value of type int, associate the name ival with that storage,
and then place an initial value of 1024 in that storage.
4

(b) The object pi has a pointer type that may hold the memory address
of an int. The address of operator (&) returns the address of the int
object ival. So pi is a pointer to an int and has been initialized with
the address of the int object ival
(c) The object pi2 has a pointer type that may hold the memory address of
an int. The new expression allocates (if successful) a single unnamed
object of type int from the free-store, initializes the unnamed object to a value of 1024, and returns the address of the object. pi2 is
initialized with that address.
(d) The object pi3 has a pointer type that may hold the memory address of
an int. The new expression allocates (if successful) 1024 contiguous
unnamed objects of type int from the free-store, and returns the address of the first object. The newly allocated objects are uninitialized.
pi3 is initialized with the returned address.
8. What does the following code fragment do? What is its significant error? (Note
that the use of the subscript operator with the pointer pia, below, is correct.)
int *pi = new int(10);
int *pia = new int[10];
while (*pi < 10){
pia[*pi] = *pi;
*pi = *pi+1;
}
delete pi;
delete [] pia;
Solution: The code given above attempts to initialize 10 int objects that pia
points to. pi points to an unnamed int object that contains a value of 10.
The test expression in the while loop compares the object that pi points
to against 10 and executes the body of the loop as long as the object has
a value less than 10. The problem is that the test fail the first time, and
the body of the loop will not be executed at all. One possible fix is the
following:
int *pi = new int(10); int *pia = new int[10]; int i = 0; while (i < 10){
pia[i] = *pi;
i++;
} delete pi; delete [] pia;
9. The behavior of the following program is undefined and likely to fail at run-time:
int foobar(int *pi) {
*pi = 1024;
return *pi;
}

int main(){
int *pi2 = 0;
int ival = foobar(pi2);
return 0;
}
What is going on here that is a problem? How might you fix it?
Solution: The problem is that pi2 has been initialized to 0 i.e., it does not point
to any object. When a call to foobar() is made, pi2 is dereferenced inside
foobar()
*pi = 1024;
Since there is no object pointed at by pi2, the dereferencing causes runtime error. Here is a possible fix:
int foobar(int *pi) {
if (pi){
*pi = 1024;
return *pi;
}
else{
cout << "Error: Cannot dereference NULL pointer! Returning 0 " << endl;
return 0;
}
}
The real fix to the problem is the test of pi in foobar(). One cannot
presume that the pointer is initialized properly but rather test it.
10. Explain the meaning of the following five definitions. Identify any illegal definitions.
a) int i; b) const int ic; c) const int *pic; d) int *const cpi;
e) const int *const cpic;
Solution:
(a) An object of type int that can be modified.
(b) A constant object of type int that cannot be modified.
(c) pic is a pointer to type const int. pic can be modified but the object
that pic point to cannot be modified.
(d) cpi is a constant pointer to type int. cpi cannot be modified but the
object that cpi points to can be modified.
(e) cpic is a constant pointer that can point to a constant int object. Neither cpic nor the object it points to can be modified.
(b), (d), and (e) are illegal definitions because constant objects must be
initialized when they are defined. Any attempts to modify a constant
object in later statements will cause error.
6

11. Which of the following initializations are legal? Explain why.


(a) int i = -1; (b) const int ic = i;
(c) const int *pic = &ic; (d) int *const cpi = &ic;
(e) const int *const cpi = &ic;
Solution:
(a) legal i is not a constant and is initialized to the integer value 1.
(b) legal ic is constant and is initialized to the value of i; it cannot be
modified after the initialization.
(c) legal pic is a pointer to a const int and is initialized with the
address of ic which is a const int; pic can be modified but the
object it points to cannot be modified.
(d) illegal cpi is a const pointer to an int but &ic is a pointer to const
int; cpi cannot be modified but the object it points to can be modified.
(e) legal cpic is a constant pointer to const int and ic is of type
const int Neither cpic nor the object it points to can be modified.
12. Based on the definitions in the previous exercise, which of the following assignments are legal? Explain why.
a) i = ic; b) pic = &ic; c) cpi = pic;
d) pic = cpic; e) cpic = &ic; f) ic = *cpic;
Solution: Left as an exercise!
13. Write the prototypes for each of the following functions:
(a) A function named compare with two parameters that are constant references to a class named matrix and with a return value of type bool
(b) A function named extract with no parameters and returns a vector of
int
Solution:
(a) bool compare(const Matrix & , const Matrix &);
(b) vector< int > extract();
14. Consider the following program.
1:
//include necessary header files
2: int a = 100;
3: int b = 200;
4:
5: void mystery(int a, int b);
6:
7: int main(){
7

8:
9:
int a = 10;
10:
int b = 20;
11:
12:
cout << "a = " << ::a << " b = " << b << endl;
13:
mystery(a,b);
14:
cout << "a = " << a << " b = " << b << endl;
15:
16:
return 0;
17:
18: }
19:
20: void mystery(int a, int b){
21:
22:
a = 1;
23:
b = 2;
24:
cout << "a = " << a << " b = " << b << endl;
25 }
(a) state the scope (by giving the line numbers) of the following identifiers.
i. The variable a in main
ii. The variable a in mystery
Solution:
i. Lines 9 18 (after as definition is complete)
ii. Lines 21 25
(b) What is the output of the program? Show the details of tracing.
Solution:
a = 100 b = 20 a = 1 b = 2 a = 10 b = 20
15. Consider you have to write a drawing program. This program would allow drawing of various objects such as points, circles, rectangles, triangles, and so on. We
want to design an Abstract Data Type (ADT) capable of representing the coordinates that would describe the position of a point in two-dimensional computer
screen. We can create a class called Point that defines a point by its coordinates
(x, y) where x is the horizontal axis, and y is the vertical axis. Since Point is
to be used in a computer program, the client needs to declare, define, and create
Point objects, obtain the individual axis positions, shift a point along either or
both axes, and compute the distance from another point. Finally, the client needs
basic input/output facilities to print a Point object on the screen, and to read one
from a keyboard.
(a) Give an appropriate and complete definition (i.e., the interface) for Point
class. You only need to give the header file.
Solution:
8

//-----point.h-----------------------------------------// A simple "Point" class definition


// Date: 09/25/1999
//-----------------------------------------------------

#ifndef POINT_H // prevent multiple inclusions #define POINT_H // of header file c


public:
// Default constructor:
// uses default values of 0.0 for the x and y coordinates
// to ensure a consistent state of the object
Point(float x = 0.0, float y = 0.0);
// Copy constructor:
//

to copy an existing object


must use call-by-reference

Point(const Point& p);


// Inspectors: Obtain the individual
// coordinate axis positions
// The functions do not modify or change the object
float getXCoordinate() const; // return x coordinate
float getYCoordinate() const; // return y coordinate
// Compute the distance from another Point.
// Does not change the invoking object or the
// object in the parameter
float computeDistance(const Point& other) const; // Compute the
// distance from
// other
// Mutators: Shift the Point along the axes
void setX(float x); // Set the x coordinate
void setY(float y); // Set the y coordinate
// Move the Point to a new position by adding
// a Point to it (Point other is used as offset)
Point& movePoint(const Point& other);
// Input-Output
void readPoint(); // read a Point object from
9

keyboard

void printPoint() const;// print a Point object on the


// screen
// Data members are made private to make them invisible to client
// programs
// A Point is represented by two floating point numbers:
// xCoordinate and yCoordinate (two-dimensional object)
private:
float xCoordinate; // horizontal axis
float yCoordinate; // vertical axis
}; #endif
(b) Implement the constructor(s) and methods to shift a point along the axes.
Solution:
//-----point.cc-----------------------------------------// Implementation for some of the Point class member functions
// Date: 09/25/1999
//----------------------------------------------------#include <iostream> #include <cstdlib> #include "point.h" using namespace std;
//----------------------------------------------------// Default constructor
// Default values: xCoordinate = yCoordinate = 0.0
//
Point::Point(float x, float y): xCoordinate(x), yCoordinate(y){
//
//
//
//
//

No code needed. It is more efficient to initialize


using an initializer list than in the body of the function.
No locals are created for x and y!
For demonstration purpose only, include a message to
signal that the constructor has been called.

cout << " Initializing: xCoordinate = " << xCoordinate


<< " yCoordinate = "<< yCoordinate << endl;
}
// Set objects xCoordinate. No error checking is performed
void Point::setX(float x) {
xCoordinate = x;
}
// Set objects yCoordinate. No error checking is performed
void Point::setY(float y) {
yCoordinate = y;
10

}
// movePoint implements shift along both axes as addition.
// Add the corresponding coordinate values to
// move the Point to a new position.
Point& Point::movePoint(const Point& other){
xCoordinate += other.getXCoordinate();
yCoordinate += other.getYCoordinate();
return *this;// enables cascaded calls
}

11

Você também pode gostar