Sei sulla pagina 1di 9

CS4 Final Practice Questions

February 26, 2007

1. struct cakeType { frostingType frosting; int numLayers; string flavor; double cost; }; cakeType bakery[100]; cakeType newCake; Given the code above, tell whether the following statements are valid or invalid. If they are invalid, give a reason why. newCake.frosting = Lemon Creme; Invalid: The member frosting of newCake is a struct. Specify the member of frosting to store the given value. bakery[35] = newCake; Valid. if(bakery[45].numLayers < 3) bakery[45].flavor = gross; Valid. bakery.cost = 45.99; Invalid: bakery is an array. There are no assignment operations on arrays. 2. Given the following function prototype in class Test: 1 2 3 const int * do_a_barrel_roll( const int arg ) const; and the following client segment in which the following is invoked: 1

int a; const int *b; Test good; b = good.do_a_barrel_roll(a); Explain the impact of the word const in each of the three locations in the function prototype. Explain in terms of the eect on a, b, and good. 1 - The int to which b points cannot be changed (return value) 2 - a cannot be changed within do a barrel roll (parameter) 3 - The state of good cannot be changed in do a barrel roll (object) 3. Suppose there is a class Sterling which has two data members, numPounds and numPence, both of which are ints. Write a constructor which takes pounds and pence as parameters and sets the data members using initialization lists. Sterling::Sterling(int pounds, int pence) : numPounds(pounds), numPence(pence) { } Write a copy constructor which copies an object, but sets the values of the new object to have 5 more pounds and 25 more pence, without using initialization lists. Sterling::Sterling(const Sterling &other) { numPounds = other.numPounds + 5; numPence = other.numPence + 25; } Why is using initialization lists good? When is using an initialization list necessary? In a constructor, the attributes of an object are set to the default values using their default constructors before entering the body of the main constructor. Therefore, using initialization lists reduces the amount of instructions executed, reducing the time needed to create the object. Also, if an attribute does not have a default constructor, then the object must be created using the initialization list. 4. Consider the following C++ class denition.

class Pastry { public: Pastry(); virtual std::string getName() const = 0; 2

virtual std::string getType() const; std::string getSugar() const; ... } class Cake : public Pastry { public: Cake(); virtual std::string getName() const; virtual std::string getType() const; virtual std::string getSugar() const; virtual void eatMe(); ... } class IceCreamCake : public Cake { public: virtual std::string getType() const; virtual void eatMe(); } (a) What is the problem with the following statement: Pastry something; Answer: You cant obtain an instance of Pastry because it is an abstract class, indicated by the pure virtual function getName() ( because it is virtual and has = 0 ). (b) Consider the following (additional method) code snippet: void eat( Cake pieceOfCake ){ pieceOfCake.eatMe(); } ... IceCreamCake iCake; eat( iCake ); ...

Are there any problems with the above code? Why or why not? Answer: The problem is the eat() function takes a Cake as a parameter instead of a pointer or reference to a Cake. This causes slicing the iCake passed into the eat() function essentially becomes a Cake since it loses all IceCreamCake-specic information. So instead, the eatMe() function from Cake is called instead of IceCreamCake. (c) Consider the following code snippet: 3

IceCreamCake iCake; Cake cake; Pastry *p1( &iCake ); Pastry *p2( &cake ); std::cout << iCake.getSugar() << std::endl; //(1) std::cout << p1->getType() << std::endl; //(2) std::cout << p2->getSugar() << std::endl; //(3) std::cout << cake.getSugar() << std::endl; //(4) ...

For the annotated statements (1-4), indicate in which class the function will be called from. 1 - Cake 2 - IceCreamCake 3 - Pastry 4 - Cake 5. Given the following declarations, show with pictures the contents of num1, num2, and num3. int num1(36); int num2(num1); int * num3 = new int(14); Now show with pictures the same contents of memory after two assignment statements. *num3 = num1 = 25; num2 = 50; 6. Is there anything wrong with this code? If so, what?

MyClass* p(new MyClass); MyClass* q = p; delete p; p = NULL; q->DoSomething();

q is a dangling pointer; the object to which it points has been deleted.

7. Declare a map called theMap that uses a key of type string and a value of type int, and write the code to iterate through the map and print the values. The format of the output should be : key: value.

Answer: #include <map> using namespace std; map<string,int> theMap; ... map<string, int>::iterator iter; for( iter = theMap.begin(); iter != theMap.end(); iter++ ) cout << (*iter).first << , << (*iter).second << endl;

8. What happens when you assert a condition that is false? Answer: The assert macro displays the condition, indicates where in the program the test failed, and aborts the program. What happens when you assert a condition that is true? Answer: The program continues execution as normal. 9. Use a string stream to convert the integer 147 into its ascii equivalent and use an ofstream to write it to a le called yawn.txt #include<iostream> #include<sstream> #include<fstream> ... ostringstream out; string result; out << 147; result = out.str(); ofstream fout(yawn.txt); fout.write( result ); fout.close();

10. Consider the following: class Vehicle{ public: Vehicle( char* name ); 5

... }; class Car:public Vehicle{ Car( char *name, int s, int p); ... private: int speeds; int passengers; };

Write the constructor for a subclass of Vehicle called Car which correctly initializes the Vehicle with a name and Car with the speeds and passengers as provided by the arguments. Answer: Car::Car( char *name, int s, int p ): Vehicle(name), speeds(s), passengers(p) 11. What are friends? How do you declare a friend function or class? If a class declares something as a friend, the friend has access to the public, protected, and private data members of that class. class product{ private: int number; public: string name; int get_number(); friend void display(); }; int product::get_number(){return number}; void display( product p ){ cout << Product: << p.name << , << p.number; } 12. Consider the following class: #include <exception> 6

... class DivideByZeroException : public exception { private: char* error_message; public: const char* what() {return error_message;} DivideByZeroException() {error_message = Error: division by zero.;} Given access to this class, and two parameters, op1 and op2, write code which divides op1 by op2, throws an exception if the code attempts to divide by zero, and catches the specic exception thrown and prints out the error message. float op1, op2; ...

try { if(op2 != 0) cout << op1 << / << op2 << = << op1/op2 << endl; else throw DivideByZeroException(); } catch (DivideByZeroException e) { cout << e.what() << endl; } 13. Consider the following: template <class T> class Min{ Min():count(0){} void insert( T value ){ assert(count>=0); if(value<min){ min=value; } } T getMin() const{ return min; 7

} private: T min; int count; }; class MyClass{ MyClass(int i); private: int val; }; Client: min <int> minInt; min <myClass> minMyClass; minInt.insert(5); minInt.insert(20); minInt.insert(6); minInt.insert(10); cout << minInt.getMin(); minMyClass.insert( MyClass(10) );

What restrictions does the Min class impose on MyClass? Answer: 1 - default constructor( for constructor ) 2 - copy constructor( for insert and getMin ) 3 - operator < (for insert) 4 - operator = (for insert) 5 - operator << (for Client) 14. Given the following class: class complex_number { private: double r; double i; public: ... ostream &operator<<(ostream &stream, const complex_number & c); };

Write the overloaded << operator with a precision of 5 digits for the real component and a precision of 3 digits for the imaginary component. Sample output: 4.5353 + 2.53i

ostream &operator<<(ostream &stream, const complex_number & c) { return stream << setprecision(5) << r << + << setprecision(3) << i << i; }

Potrebbero piacerti anche