midterm sample

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) 2 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); 1

Upload: vibha

Post on 17-Jan-2016

7 views

Category:

Documents


0 download

DESCRIPTION

this is useful

TRANSCRIPT

Page 1: Midterm Sample

1 CS2620 Review Topics for Midterm

1. Identifying classes and objects from problem description. C++ class definitionsyntax. 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 aclass member. Different type of class constructors. (see class notes, Section 6.3of the text book)

3. Function overloading, default arguments (pages 157-162, 288-289 of the textbook and class notes), default constructors, copy constructors, type conversionconstructors and “explicit” declaration (pages 157-162, 288-289 of the text bookand class notes)

4. Overloaded operator function definition and implementation, friend functionsand their proper use, reference return from a function and call cascading (Chapter8 and class notes)

5. Storage classes: characteristics of local static, global, stack, and heap memory,pointer variable declaration, de-referencing pointers, pointer arithmetic, dynamicmemory allocation and deallocation, constant pointers and pointer to constants,pointer parameters, pointers and arrays, pointer arithmetic (Chapter 12 and classnotes)

2 Sample problems for Midterm

Below are sample problems for the midterm test. Although these problems are similarto the type of problems you can expect on the test, please be advised that the test is notlimited 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 namedPerson 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);

1

Page 2: Midterm Sample

which members would you declare in public and which members would youdeclare in private sections of the class? Explain your choice.

3. A Clock object has three attributes: hour, minute, and second. The followingdesign requirements are presented to you

• Constructor(s) are required to create clock objects with user-specified val-ues for hour, minute, and second. In addition, a default constructor isneeded as in the following code example:

Clock c1; // use default values to construct c1 ClockClock 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 hourc2.getMinute(); // returns minutec2.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 theClock class as per specification givenabove.

(b) Implement thedisplay() setClock(), andtick() 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 op-erator.a) a memberwise copy of all the data membersb) a deep copy of all the datac) neither, it will not compile because you need to provide the assignmentoperatord) none of the above

(b) In C++, the same name can be associated with multiple definitions. Thecompiler selects the appropriate definition by:a) looking at the function signatureb) looking at the definitions that were defined in the same scopec) looking at the return typed) all of the above

2

Page 3: Midterm Sample

(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 whileat 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 fromabove, answer the following questions:

3

Page 4: Midterm Sample

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 constructorb) copy constructorc) default constructor followed by the copy constructord) default constructor followed by the assignment operator

ii. With this new main program, the program now prints:a) True-Trueb) True-Falsec) False-Trued) False-False

6. Why do you think the built-in array does not support the assignment of one arrayto another? What information is required to support this operation?

Solution: The name of a built-in array, when appears in an expression, is im-plicitly converted to aconst pointer, and it points to the first element in thearray. Since aconst object cannot be assigned to after its initialization, wemay not assign one array with another.The language was not designed to handle array assignments. The compilerwould have to know the length of the arrays at run-time, to generate codeto 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 storageto hold a value of typeint, associate the nameival with that storage,and then place an initial value of 1024 in that storage.

4

Page 5: Midterm Sample

(b) The objectpi has a pointer type that may hold the memory addressof anint. Theaddress ofoperator (&) returns the address of theintobjectival. Sopi is a pointer to anint and has been initialized withthe address of theint objectival

(c) The objectpi2 has a pointer type that may hold the memory address ofanint. Thenew expression allocates (if successful) a single unnamedobject of typeint from the “free-store’, initializes the unnamed ob-ject to a value of 1024, and returns the address of the object.pi2 isinitialized with that address.

(d) The objectpi3 has a pointer type that may hold the memory address ofanint. Thenew expression allocates (if successful) 1024 contiguousunnamed objects of typeint from the “free-store’, and returns the ad-dress 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? (Notethat the use of the subscript operator with the pointerpia, 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 10int objects thatpiapoints to.pi points to an unnamedint object that contains a value of 10.The test expression in thewhile loop compares the object thatpi pointsto against 10 and executes the body of the loop as long as the object hasa value less than 10. The problem is that the test fail the first time, andthe body of the loop will not be executed at all. One possible fix is thefollowing:

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;

}

5

Page 6: Midterm Sample

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 thatpi2 has been initialized to 0 i.e., it does not pointto any object. When a call tofoobar() is made,pi2 is dereferenced insidefoobar()

*pi = 1024;

Since there is no object pointed at bypi2, the dereferencing causes run-time 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 ofpi in foobar(). One cannotpresume that the pointer is initialized properly but rather test it.

10. Explain the meaning of the following five definitions. Identify any illegal defini-tions.

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 typeint that can be modified.(b) A constant object of typeint that cannot be modified.(c) pic is a pointer to typeconst int. pic can be modified but the object

thatpic point to cannot be modified.(d) cpi is a constant pointer to typeint. cpi cannot be modified but the

object thatcpi points to can be modified.(e) cpic is a constant pointer that can point to a constantint object. Nei-

thercpic nor the object it points to can be modified.(b), (d), and (e) are illegal definitions because constant objects must beinitialized when they are defined. Any attempts to modify a constantobject in later statements will cause error.

6

Page 7: Midterm Sample

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 ofi; it cannot be

modified after the initialization.(c) legal –pic is a pointer to aconst int and is initialized with the

address ofic which is aconst int; pic can be modified but theobject it points to cannot be modified.

(d) illegal –cpi is aconst pointer to anint but&ic is a pointer toconstint; cpi cannot be modified but the object it points to can be modified.

(e) legal –cpic is a constant pointer toconst int and ic is of typeconst int Neithercpic nor the object it points to can be modified.

12. Based on the definitions in the previous exercise, which of the following assign-ments 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 namedcompare with two parameters that are constant refer-ences to a class namedmatrix and with a return value of typebool

(b) A function namedextract with no parameters and returns avector ofint

Solution:

(a) bool compare(const Matrix & , const Matrix &);

(b) vector< int > extract();

14. Consider the following program.

1: //include necessary header files2: int a = 100;3: int b = 200;4:5: void mystery(int a, int b);6:7: int main(){

7

Page 8: Midterm Sample

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 variablea in main

ii. The variablea in mystery

Solution:

i. Lines 9 – 18 (aftera’s 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 draw-ing of various objects such as points, circles, rectangles, triangles, and so on. Wewant to design anAbstract Data Type (ADT)capable of representing the coor-dinates that would describe the position of apoint in two-dimensional computerscreen. We can create a class calledPoint that defines a point by its coordinates(x,y) wherex is the horizontal axis, andy is the vertical axis. SincePoint isto be used in a computer program, the client needs to declare, define, and createPoint objects, obtain the individual axis positions, shift a point along either orboth axes, and compute the distance from another point. Finally, the client needsbasic input/output facilities to print aPoint object on the screen, and to read onefrom a keyboard.

(a) Give an appropriate and complete definition (i.e., the interface) forPointclass. You only need to give the header file.

Solution:

8

Page 9: Midterm Sample

//-----point.h------------------------------------------// A simple "Point" class definition// Date: 09/25/1999//-----------------------------------------------------

#ifndef POINT_H // prevent multiple inclusions #define POINT_H // of header file class Point {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 coordinatefloat 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 coordinatevoid 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 keyboard

9

Page 10: Midterm Sample

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 axisfloat 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 object’s xCoordinate. No error checking is performedvoid Point::setX(float x) {

xCoordinate = x;}

// Set object’s yCoordinate. No error checking is performedvoid Point::setY(float y) {

yCoordinate = y;

10

Page 11: Midterm Sample

}

// 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