CS 150 Final
What prints? class Employee { public: Employee() = default; Employee(const string& n, double s) : name(n), salary(s) {} void setName(const string& n) { name = n; } void setSalary(double s) { salary = s; } string getName() const { return name; } double getSalary() const { return salary; } private: string name; double salary = 0; }; class Manager : public Employee { public: Manager() = default; Manager(double b) { bonus = b; } Manager(const string& n, double s, double b) : Employee(n, s), bonus(b) {} void setBonus(double b) { bonus = b; } void print() const; private: double bonus; } ; void Manager::print() const { cout << getName() << " $ " << getSalary() << "; Bonus: " << bonus << endl; } int main() { Manager m1; Manager m2(1000); Manager m3("Peter", 30000, 1000); m2.print(); }
$ 0; Bonus: 1000
In line 2, what is the explicit argument? 1. string {"happy"}; 2. auto pos = s.find('y');
'y'
Which operator is implemented here? class ForX { int data; }; //////???////// { --data; return *this; }
--a
Here is a class hierarchy for different card games. The Hand Class AAs you know, C++ sometimes uses different terminology from Java and other Object-Oriented languages. According to this design, and using both C++ and traditional terminology, the Hand class may be described as a _____________________. There may be more than once correct answer.
-abstract class -super class -base class
How many variables appear in the following code segment? int n = 5; int& r1 = n; auto& r2 = r1; r1 = 4; r2 = 3; cout << n << endl;
1
What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << *p << endl;
1
Match each item with the correct definition below. 1. How arrays are passed to functions 2. int * const array 3. x = a[0]; for (auto e: a) if (e > x) x = e; 4. auto p = a; while (p != end(a)) p++;
1. by address 2. Elements in may be modified; pointer may not be 3. Extreme values algorithm 4. Iterator-based loop
Match each item with the correct definition below. 1. What happens to an array when passed to a function 2. const int * const array 3. for (auto e : a) . . 4. cout << a[0]; while (i < len) cout << ", " << a[i++];
1. decays 2. Neither pointer nor elements in may be modified 3. A range-based loop 4. Fencepost algorithm
What prints here? class Car { double speed; public: Car(); Car(double s); double get() const; }; Car::Car() { speed = 10; } Car::Car(double s) { speed = s; } double Car::get() const { return speed; } int main() { Car c1, c2(5); cout << c1.get() << c2.get() << endl; }
105
What is printed here? #include <iostream> using namespace std; int main(){ int x = 20, y = 10;y = x--; cout << x << ", " << y << endl;
19, 20
What is printed? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] < a[x]) x = n; } return x; } int main() { int a[] = {4, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; }
3
What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) size_t len(const int* a, const int* b) { return b - a; } int main() { int a[] = {2, 4, 6, 8}; cout << len(begin(a), end(a)) << endl; }
4
What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) int main() { int a[] = {2, 4, 6, 8}; cout << sizeof(a) / sizeof(a[0]) << endl; }
4
Which line throws an exception because of range checking? 1. string s = "holey moley"; 2. auto len = s.size(); 3. auto a = s.front(); 4. s.at(len) = a; 5. s[len] = 'c';
4
Which lines cause syntax errors? string s {"shiver me timbers"};
4 6
What does this code print? int main() { auto p1 = make_shared<int>(42); auto p2 = p1; cout << *p1 << endl; cout << *p2 << endl; (*p2)++; cout << *p1 << endl; }
424243
Which line produces undefined behavior? 1. string s = "holey moley"; 2. auto len = s.size(); 3. auto a = s.front(); 4. s.at(len) = a; 5. s[len] = 'c';
5
How many (int) elements are in this array? int a[2][3];
6
What prints? int x = 0; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (const auto& r : a) for (const auto& c : r) x++; cout << x << endl;
6
Which of these lines are illegal? 1. int n1 = 4; 2. double n2 = 3.145; 3. unsigned char n3 = 158; 4. int n4 = n2; 5. int& r1 = n1; 6. int& r2 = n2; 7. double& r3 = n1; 8. const int& r4 = n2
6 7
What prints when this runs? int a[2][3] = {1, 2, 3, 4, 5, 6}; cout << a[0][2] + a[1][2] << endl;
9
To use any of C++ smart pointer types, include the header:
<memory>
Manager is derived from Employee. Which of the following statements are true?
A Manager constructor can pass data to an Employee constructor
Which one of the following is an example of the "substitution principle"?
A derived class object can be used in place of a base-class object.
What is the name for this algorithm? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) {out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; }
A fencepost algorithm
Which of these are part of the implementation? class Time { Time(); long get() const; void set(long); private: long seconds; };
All of these are part of the implementation
Why is the command-line argc always at least 1?
Because argv[0] is the name of the program running
C++
Bjarne Stroustrup
Below is a class hierarchy for card games. Assuming that these are the only classes and that the concrete classes are correctly completed, which of the following definitions will not compile? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; virtual int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . };
BlackjackHand* h = new Hand;
What does a derived class inherit from its base class?
Both data and behavior
How can a derived class override a base class function?
By providing a new implementation for a function with the same name and parameter types
Which one of the following Car member functions is called by this statement? AeroCar acar1(2000.0, 200.0); class Car { public: Car(); Car(double); void setSpeed(double); double getSpeed() const; }; class AeroCar : public Car { public: AeroCar(); AeroCar(double); AeroCar(double, double); void setHeight(double); double getHeight() const; }; AeroCar::AeroCar(double h, double s : Car(s), height(h) { } int main() { AeroCar acar(2000.0, 200.0); }
Car(double)
The Pet base class defines void setName(const string&). Cat is derived from Pet, but does not define setName(). What is true?
Cat class inherits the setName function.
The following code: #include <string> class Xynoid { double a{3.14}; int b = 42; std::string c; }; int main() { Xynoid x; }
Compiles and links. All members initialized
Which of these statements apply to C++?
Compiles to native code Produces native code that runs on CPU more efficient than Java or Python
What is printed? class Counter { public: Counter(int c) : counter(c) {} virtual void add(int n) { counter += b; } void display() { cout << "Count->" << counter; } private: int counter; }; class DoubleCounter : public Counter { public: DoubleCounter(int c) : Counter(c * 2) {} void add(int n) { Counter::add(n * 2); } }; int main() { DoubleCounter counter(10); counter.add(5); counter.display(); }
Counter->30
What happens here? char *s1 = "CS150"; char s2[] = s1; s2[0] = 'X'; cout << s1 << endl;
Does not compile
What is printed here? #include <iostream> using namespace std; int main() { int n = 2;cout << n++++ << endl; }
Does not compile
What prints when this code is run? #include <string> #include <iostream> #include <vector> using namespace std; class Shape { public: virtual void iam() const; }; class Square : public Shape { public: void iam() const; }; class Oval: public Shape { public: void iam() const; }; void Shape::iam() const { cout << "Shape"; } void Square::iam() const { cout << "Square"; } void Oval::iam() const { cout << "Oval"; } void iam(const Shape& s) { s.iam(); } int main() { vector<Shape&> v = {Shape(), Square(), Oval()}; for (auto& e : v) iam(e); cout << endl; }
Does not compile
What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1; cout << *p2; (*p2)++; cout << *p2; }
Does not compile (illegal)
What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1; cout << *p2; (*p2)++; cout << *p2; }
Does not compile (illegal)
Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum = 0; for (auto e : a) sum += e; cout << "sum->" << e << endl;
Does not compile; e is undefined.
The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator which returns the address of the Point object in memory? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point operator@(const Point& p) { return __________________; }
Does not compile; uses a non-operator symbol.
What does this code mean? class X { double x = Y().balance(); . . . };
Each X object uses- a Y object
The Manager class is derived from the Employee class. Manager defines a constructor, but does not explicitly call an Employee constructor. Which constructor is called by the Manager constructor? class Employee { public: Employee(); Employee(const string&); Employee(double); Employee(const string&, double); };
Employee();
Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(end(a), begin(a)) << endl; }
Endless loop when run; likely crashes.
What does this code mean? class X { Y y; . . .};
Every X object has-a Y object
What does this code mean? class X : public Y { . . . };
Every X object is-a Y object
A 2D array address expression is the equivalent of:
False
A pointer that goes out of scope before deleting the memory it points to is called a double delete.
False
A pointer-like object that can be used to automatically manage memory allocated on the heap is called a raw pointer.
False
A unique_ptr uses a reference count to manage how many pointers point to an object.
False
An abstract class is a class that contains only virtual member functions.
False
An abstract class may, but is not required to, override its pure virtual (abstract) member functions.
False
Assuming p is a pointer to a single variable allocated on the heap, the statement delete[] p; returns the allocated memory back to the operating system for reuse.
False
C-string assignment uses the strcat() function.
False
Freeing unused memory that was allocated elsewhere in your program is done in C++ using a garbage collector.
False
If p points to the first element in [1, 3, 5] then cout << *p++ prints 3.
False
If the new operator cannot allocate memory, C++ returns nullptr.
False
If your class does not have a constructor, the compiler will synthesize a working constructor for you.
False
In C++ the only difference between structures and classes is that member functions are public by default in classes.
False
In C++, as in Java pure virtual member functions may not have an implementation.
False
In a partially-filled array, the capacity represents the effective size of the array.
False
Inheritance enforces the principle of data hiding.
False
Initialization of data members occurs according to the order they are listed in the initializer list.
False
It is illegal to construct an instance of an abstract class.
False
Memory for local variables is allocated on the stack when their definitions are encountered during runtime. This is known as dynamic allocation.
False
Mutator member functions should always end in the keyword const.
False
Object behavior is implemented by data member.
False
Polymorphism enforces the principle of data hiding.
False
Private inheritance models an IS-A relationship between classes.
False
Requesting a block of memory from the operating system as the program runs is known as automatic allocation.
False
Requesting a block of memory from the operating system as the program runs is known as static allocation.
False
Smart pointers may point to objects allocated on the stack.
False
The attributes of an object refers to the combination of values stored in its data members.
False
The composition relationship is informally known as is-a.
False
The elements of a vector may be allocated on the stack.
False
The expression *p++ means the same as (*p)++.
False
The implementation of a member function from the Time class would look something like this: int Time.hours() const {...}.
False
The istream class in the C++ standard library uses multiple inheritance.
False
The statement new int; allocates a default-initialized integer on the heap.
False
The statement new int{3}; allocates an array of three integers on the heap.
False
To allocate memory on the stack, C++ uses the new operator.
False
Using a pointer to access the memory it points to after the pointer has been deleted is called a double delete.
False
Using a pointer to access the memory it points to after the pointer has been deleted is called a memory leak.
False
Using public inheritance to derive Stack from vector is a good design because vector provides all of the capabilities that a Stack requires.
False
Using structures for user-defined types means that you can change the data representation without affecting the users of your data type.
False
Using structures for user-defined types means that you can enforce restrictions on data member access.
False
What Java calls a static method is called a pure virtual member function in C++.
False
When inserting a value into a partially-filled array, in ascending order, the insertion position may be the same as capacity.
False
When inserting an element into a partially-filled array, it is an error if size < capacity.
False
With inheritance, the class you build upon is called a subclass in C++.
False
You must use the ordinary meaning of an operator when you overload it. It would be impossible to redefine subtraction to mean addition, for instance.
False
Examine this program from your reader and match the definitions to the numbers. Each number is matched exactly once. Find the best definition.
Function call #9 Variable definition #7 Output Statement #10 Namespace directive #3 Input statement # 8 Parameter # 14 Program entry point # 5 standard library headers # 2
Examine the class hierarchy below. Assume that both derived classes are concrete and completely defined. Which line of code is illegal: class Hand { std::vector<Card> cards; public: Hand() = default; virtual ~Hand() = default; void add(const Card&); virtual int score() const = 0; virtual void sort(); bool operator<(const Card& rhs) const; }; class PokerHand : public Hand { . . . } class BlackjackHand : public Hand { . . . }
Hand h
Match each item with the control structure best equipped to handle it
Handle an on or off condition - if-else statements handle processing for a group of radio buttons - sequential if statements set a variable to one of two possible values - the conditional operator
Examine the following UML diagram. Assume that the following code appears inside a member function or constructor of the Student class. Which of these statements would be legal?? name = "Bill Gates"; // I setName("Bill Gates"); // II name = name.substr(1); // III studentID = 123L; // IV studentID = getID() * 2; // V
II, IV and V
Below is insert(), a template function that works with a partially-filled array. The function inserts the argument e into the array, in sorted order. The function returns true if it succeeds, false otherwise. The function contains an error; what is the error? template <typename T> bool insert(T* a, size_t& size, size_t MAX, T e) { if (size < MAX) return false; size_t i = 0; while (i < size) { if (a[i] > e) break; i++; } for (j = size; j > i; j--) a[j] = a[j - 1]; a[i] = e; size++; return true; }
If there is room to insert, the function returns false instead of true. It should say if (size == MAX)
What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << p[1][2] << endl;
Illegal; will not compile
Below is a class hierarchy for card games. What happens when showScore() is called? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . }; void showScore(const Hand& h) {\ cout << h.score() << endl; } . . . PokerHand ph; . . . showScore(ph); // what happens here?
It calls the Hand::score() function because score() is not virtual
Below is a class hierarchy for card games. What happens when showScore() is called? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; virtual int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . }; void showScore(const Hand* h) { cout << h.score() << endl; } . . . PokerHand ph; . . . showScore(&ph); // what happens here?
It calls the PokerHand::score() function if one has been defined
What is true about a mutator member function?
It changes one or more data members
What is true about an accessor member function?
It returns information about an object's state
FORTRAN
John Backus
Unix and C
Ken Thomson and Dennis Ritchie
identify the following variables as an L-value, R-value or Non-modifiable L-value const double PRICE = 7.95 double a = PRICE; double b = 5.95; a = b;
Line 1: 7.95 - R-Value Line 2: PRICE - R-Value Line 3: b - L-Value Line 4: b - R-Value
Examine the following portion of code and then answer the questions that follow. -Which line allocates a variable on the heap -Which line creates a sharing pointer? -Which line causes a memory leak? -p1 points to an object with
Line A Line B None of These programmer defined duration
What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; }
Line Cat b; does not compile. No suitable constructor.
Which among the following is the legal way of implementing the constructor of the Manager class that passes parameters to a base-class constructor? class Employee { public: Employee(); Employee(const string&); Employee(double); Employee(const string&, double); private: string name; double salary; }; class Manager : public Employee { public: Manager(); Manager(const string& d, const string& n, double s); private: string department; };
Manager::Manager(const string& d, const string& n, double s) : Employee(n, s) { department = d; }
Consider the following classes. The Vehicle class is a base class. The Car, Truck, and Motorcycle class inherit from the Vehicle class. The Sedan and SUV classes inherit from the Car class. Which of the following lists all the types of objects that cannot be passed into the function calculate_registration_fee(Car& car)?
Motorcycle, Truck, and Vehicle objects
Pascal
Nicholas Wirth
Which member function(s) must be overridden in Hobbit? class Creature { public: Creature(const string& name); virtual string name() const final; virtual string skills() const; virtual void addSkill(const string& skill); void print() const; }; class Hobbit : public Creature { . . .};
None of them
This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] != 0 && p[2] != 0) cout << p[0] / p[1] / p[2] << endl; delete[] p; }
None of these
Which line correct creates a smart pointer that points to the variable x? int x = 42;
None of these
Which line correctly creates a smart pointer that points to the variable x? int x = 42;
None of these
Below is a class hierarchy. Which assignments are illegal? class Widget { . . . }; class Label: public Widget { . . . }; class Button: public Widget { . . . }; class Text: public Widget { . . . }; class TextArea: public Text { . . . }; class TextLine: public Text { . . . }; class Container: public Widget { . . . }; class Canvas: public Container { . . . }; class Window: public Container { . . . };
None of these are illegal
Examine this code. What goes on the blank line? void f() { int *p = new int[3]{1, 2, 3}; . . . ___________________ }
None of these is correct (WRONG)
Suppose that we have a Question class that contains two data members - a query and answer both of which are type string. The NumericQuestion class is derived from Question. Which of the following is true?
NumericQuestions contains both a query and an answer string.
This portion of code: #include <iostream> using std::cout; int main() {cout << "Hello CS 150" << endl;}
Other syntax error
What is true about this inheritance hierarchy (using both C++ and traditional, classic OO terminology)? Assume that Party has a member function (which Person overrides), declared as: virtual void print() = 0;
Person is a derived class Organization is a superclass Organization is a subclass Party is an abstract class Party is a base class
Below is a class hierarchy for card games. Assuming that these are the only classes and that the concrete classes are correctly completed, which of the following definitions will not compile? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; virtual int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . };
PokerHand* = new Hand;
ChoiceQuestion is derived from the Question base class . ChoiceQuestion overrides the display() function defined in the Question base class. Which of the following will call the base class display() function from the ChoiceQuestion display() function?
Question::display()
What prints when this code is run? #include <string> #include <iostream> using namespace std; class Shape { public: virtual void iam() const; }; class Square : public Shape { public: void iam() const; }; class Oval: public Shape { public: void iam() const; }; void Shape::iam() const { cout << "Shape"; } void Square::iam() const { cout << "Square"; } void Oval::iam() const { cout << "Oval"; } void iam(Shape s) { s.iam(); } int main() { iam(Shape()); iam(Square()); iam(Oval()); cout << endl; }
ShapeShapeShape
What prints when this code is run? #include <string> #include <iostream> using namespace std; class Shape { public: virtual void iam() const; }; class Square : public Shape { public: void iam() const; }; class Oval: public Shape { public: void iam() const; }; void Shape::iam() const { cout << "Shape"; } void Square::iam() const { cout << "Square"; } void Oval::iam() const { cout << "Oval"; } void iam(const Shape& s) { s.iam(); } int main(){ iam(Shape()); iam(Square()); iam(Oval()); cout << endl; }
ShapeSquareOval
What prints here? class Car { public: Car() = default; Car(double s): speed(s) {} double getSpeed() const { return speed; } private:double speed = 0; }; class AeroCar : public Car { public: AeroCar() = default; AeroCar(double h, double s) : Car(s * 2), height(h) {} void display() const; private: double height = 0; }; void AeroCar::display() const { cout << "Speed: " << getSpeed() << "; Height: " << height << endl; } int main() { AeroCar acar1(2000, 200); acar1.display(); }
Speed: 400; Height: 2000
The Car class inherits from the Vehicle class. The Car class contains one constructor which does not call a particular Vehicle constructor. Which of the following is true?
The Vehicle default constructor is implicitly called by the Car constructor.
Below is endsWith(), a template function that works with two partially-filled arrays. The function returns true if the array a "ends with" the same elements as the array b, false otherwise. The function contains an error; what is the error? template <typename T>bool endsWith(T* a, size_t sizeA, T* b, size_t sizeB) { if (sizeA < sizeB) return false; size_t diff = sizeA - sizeB; for (size_t i = 0; i < sizeB; i++) if (a[i + diff] != b[i]) return false; return true; }
The arrays a and b should be const T*
Which members often use the modifier explicit in their declaration?
The conversion constructor
What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat() = default; Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; }
The does compile; it prints "Bill".
The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; ostream& operator<<(ostream& out, const Point& p) { return out << '(' << p.x() << ", " << p.y() << ')'; }
There is no error; it works fine.
A 2D array is a 1D array whose elements are also 1D arrays.
True
A class definition ends with a semicolon.
True
A constructor always has the same name as the class, and no return type.
True
A function that is marked with the keyword inline must be places in the header file.
True
A pointer that goes out of scope before deleting the memory it points to is called a memory leak.
True
A pointer-like object that can be used to automatically manage memory allocated on the heap is called a smart pointer.
True
A unique_ptr can refer to a dynamic array.
True
A unique_ptr may transfer its ownership to another unique_ptr.
True
A vector variable may be allocated on the stack.
True
Assuming p is a pointer to a single variable allocated on the heap, the statement delete p; returns the allocated memory back to the operating system for reuse.
True
Assuming p is a pointer to the first variable in an array allocated on the heap, the statement delete[] p; returns the allocated memory back to the operating system for reuse.
True
C-strings are often needed to interoperate with legacy C libraries.
True
C-strings use the strcat() function for concatenation.
True
Command line arguments that start with a hyphen are usually called switches.
True
Freeing unused memory that was allocated elsewhere in your program is done in C++ using manual memory management.
True
If a class is abstract, you may create a pointer of that class.
True
If you write a working constructor for your class, C++ will remove the synthesized default constructor.
True
In C++ pure virtual member functions may have an optional implementation.
True
In a partially-filled array, the size represents the effective size of the array.
True
Inheritance allows you to build a new class by using an existing class as a starting point.
True
It is always a logic error for a derived class to redefine a non-virtual function.
True
Memory for global variables is allocated when the program is loaded from disk. This is known as static allocation.
True
On the command line, argc is the count of arguments including the program itself.
True
Overloaded operators are functions that use special names that begin with the keyword operator.
True
Putting the keyword final at the end of the class heading prohibits the creation of subsequent derived classes.
True
Smart pointers automatically delete the memory they point to at the appropriate time.
True
The algorithm that finds the address of the smallest element in an array is called an extreme values algorithm.
True
The function mystery(const int*, const int*) likely employs an iterator loop.
True
The implementation of a class includes all private data members in the header file.
True
The interface of a class includes all public items in the header file.
True
The iostream class in the C++ standard library uses multiple inheritance.
True
The library function begin(a) returns a pointer to the first element in the array a.
True
The member function int& hours(); provides read-write access to the hours property (however it is stored).
True
The statement new int[3] = {1, 2, 3}; is a syntax error.
True
The statement new int{3}; allocates a single initialized integer on the heap.
True
The statement new int{}; allocates a default-initialized integer on the heap.
True
To transfer a unique_ptr to a vector, use push_back along with the move() function.
True
Using a pointer to access the memory it points to after the pointer has been deleted is called a dangling pointer.
True
Using public inheritance to derive Stack from vector is a problem because a Stack is really not a vector.
True
What Java calls an abstract method is called a pure virtual member function in C++.
True
When passing a 2D array to a function, the array parameter must explicitly list the size for all dimensions except for the first, like: void f(int a[][3], size_t n);
True
With classes, the public interface includes the member functions that allow clients to access object data in a safe way.
True
You may add = default; to the prototype for a default constructor to retain the synthesized version in the presence of other overloaded constructors.
True
Your operating system's command processor is known as the shell.
True
What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1.release(); cout << *p2; (*p2)++; cout << *p1; }
Undefined behavior
The Department of Motor Vehicles uses a vehicle registration program that declares a Vehicle class as a base class. The Car class and the Truck class both inherit from the Vehicle class. Which types of objects can be passed to the function register(Vehicle& v)?
Vehicle, Car and Truck objects
string::size_type
What type in the variable len? 1. string s = "holey moley"; 2. auto len = s.size(); 3. auto a = s.front(); 4. s.at(len) = a; 5. s[len] = 'c';
What is printed? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } int a[] = {1,2,3,4,5,1}; mystery(cout, a, 4) << endl;
[1, 2, 3, 4]
Below you'll find a C++ class hierarchy. All classes (including Card) are correctly and fully implemented. Match the following descriptions. [1] class PokerHand [2] ~Hand() [3] add() [4] sort()
[1] derived class [2] destructor [3] mutator [4] mutator
Below you'll find a C++ class hierarchy. All classes (including Card) are correctly and fully implemented. The Hand class: [1] may not override the accessor [2] inherits, but cannot override, the mutator [3] is a(n) [4] must override [5] may, but need not, override
[1] get [2] add [3] concrete class [4] score [5] sort
Below you'll find a C++ class hierarchy. All classes (including Card) are correctly and fully implemented. The PokerHand class: [1] may not override the accessor [2] inherits, but cannot override, the mutator [3] is a(n) [4] must override [5] may, but need not, override
[1] get [2] add [3] concrete class [4] score [5] sort
Below you'll find a C++ class hierarchy. All classes (including Card) are correctly and fully implemented. The Hand class: [1] relationship with vector: [2] contains an abstract function [3] is a derived class of [4] as a(n) [5] implements the accessor [6] is the derived class of
[1] has-a [2] score [3] none [4] abstract class [5] get [6] none
Below you'll find a C++ class hierarchy All classes (including Card) are correctly and fully implemented. Match the following descriptions. [1] score() [2] class Hand [3] Hand() [4] sort()
[1] pure virtual function [2] abstract base class [3] default constructor [4] mutator (may be overridden)
Examine the following code (which compiles). Answer the questions about the overloaded operators. struct ForX { ForX& operator^=(const ForX&); const ForX operator-() const; const ForX operator&(const ForX&) const; }; const ForX operator~(const ForX&); ForX* operator&(const ForX&); [1] ForX::operator~ [2] operator~ [3] operator& [4] side-effect operator
[1] unary member operator [2] unary non-member operator [3] nary non-member operator [4] ForX::operator^=
[1] Elements always allocated on the heap [2] const int *array [3] sizeof(a) / sizeof(a[0]) [4] x = 0; for (auto e : a) x += e;
[1] vector [2] Elements may not be modified; pointer may be [3] Elements in array using arithmetic [4] cumulative algorithm
What is printed when this runs? #include <iostream> using namespace std; int main() { int a = 3, b = ++a; cout << "a->" << a << ", b->" << b << endl; }
a->4, b->4
Assume you have a partially filled array a, with variables size and MAX (capacity). To append value to the array, which of these assignments is correct?
a[size] = value;
What is g()? class X { public: X(int); void f() const; int g() const; void h(int); };
accessor
What type of member function is toString()? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; };
accessor
Examine the class hierarchy below. Assume that both derived classes are concrete and completely defined. Which of the following member functions cannot be overridden in the derived classes? class Hand { std::vector<Card> cards; public: Hand() = default; virtual ~Hand() = default; void add(const Card&); virtual int score() const = 0; virtual void sort(); bool operator<(const Card& rhs) const; }; class PokerHand : public Hand { . . . } class BlackjackHand : public Hand { . . . }
add()
Which member function(s) may be overridden in Hobbit? class Creature { public: Creature(const string& name); virtual string name() const final; virtual string skills() const; virtual void addSkill(const string& skill); void print() const; }; class Hobbit : public Creature { . . . };
addSkill(), skills()
What is true about the command line in C++? I. The first argument is the name of the program II. Command line arguments are passed in an array III. Use main(int argc, char* argv[])
all of these are true
The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Which of the following operators (which are all valid) cannot be used, assuming that the BigNum constructor is non-explicit? BigNum a{9.2573e27}; auto c = a / 100.0;
all of these can be used
This code illustrates the - idiom if (n%2==1) cout << "Odd" << endl; else cout << "Even" << endl;
alternate action
The program a.out is run like this: ./a.out alex brent chris rodger 32 33 44 78
argc is 9 and argv[0] is "./a.out"
Given this declaration, which line below is illegal? auto p1 = unique_ptr<int>(new int{42});
auto p2 = p1;
if a and c are both false, which expressions must be evaluated? if ( a && b || c && d || e)
b d e
Examine the following class hierarchy: The ostream class is the/a ___________ class of ofstream.
base
Expressed in C++ terminology, the relationship between the Food class and the CherryPie class is one of _____________ (Food) and ________________ (CherryPie).
base class, derived class
Below is a declaration for a partially-filled array. What is the correct prototype for a function add() that appends a new element to the end of the array and returns true if successful? const size_t MAX = 100; double nums[MAX]; size_t size = 0;
bool add(double a[], size_t& size, size_t MAX, double e);
If a and b are true, which expressions need not be evaluated? if ( a && b || c && d || e)
c d e
A(n) ___________ is a template or blueprint specifying the data attributes and behaviors for a group of similar objects.
class
___________________ is one of the primary mechanisms that we use to understand the natural world around us. Starting as infants we begin to recognize the difference between categories like food, toys, pets, and people. As we mature, we learn to divide these general categories or classes into subcategories like siblings and parents, vegetables and dessert.
classification
What happens here? #include <iostream> using namespace std; int main() { double bottles, volume = bottles * 2;cout << volume << endl; }
compiles and links. Output is unpredictable.
This portion of code #include <iostream> using std::cout; int main() {cout << "Hello CS 150/n";}
compiles, runs, prints output with a newline
The attributes of this class are model and price. In C++ terminology, these are called: class Mobile { std::string model; double price; public: . . . };
data members
Which element is private? class Val { int data_; public: Val(int); int get() const; void print() const; }; void Val::get() { return data_; } Val::Val(int n) { data_ = n; } void Val::print() const { cout << data_; }
data_
In the reading you learned about five concepts related to variables. Line 3 is ______________. More than one answer may be required. double c = 3.15;
declaration definition initialization
Examine this code. What goes on the blank line? void f() { int *p = new int{3}; . . . ___________________ }
delete p;
The ostream class is the/a ___________ class of ios.
derived
Examine the following class hierarchy: The fstream class is the/a ___________ class of istream.
descendant
What prints here? const char *a = "dog", *b = a; if (strcmp(a, b)) cout << "dog == dog" << endl; else cout << "dog != dog" << endl;
dog != dog
The real number types built into the c++ language include:
double float long double
Which of these is an example of the principle of substitutability? void f1(fstream& out) { . . .} void f2(int n) { . . . } void f3(const string& s) { . . . } void f4(ios& i) { . . . }
f4(cout);
A 2D array address expression is the equivalent of: *(address + (row * height + col))
false
A function that is marked with the keyword inline should be placed in the implementation .cpp file.
false
A pointer that goes out of scope before deleting the memory it points to is called a dangling pointer.
false
A shared_ptr can refer to a dynamic array.
false
A vector generally has higher performance than an array.
false
An abstract class is a class that contains no data members.
false
Assuming p is a pointer to a single variable allocated on the stack, the statement delete p; returns the allocated memory back to the operating system for reuse.
false
Consider the Shape class hierarchy, along with Circle, Square and Star from your text. The Shape class is a concrete class.
false
If a derived class redefine a non-virtual base-class function it causes a syntax error.
false
If the new operator cannot allocate memory, C++ returns nullptr
false
In C++ the only difference between structures and classes is that member functions are private by default in structures.
false
In a partially-filled array, all of the elements contain meaningful values
false
In a partially-filled array, the size represents the allocated size of the array.
false
Memory for global variables is allocated when the program is loaded from disk. This is known as dynamic allocation.
false
Programs written for embedded devices usually use the C++ library string type, rather than the older C-string type.
false
Putting the keyword final at the end of a non-virtual member function heading prohibits derived classes from overriding that function.
false
The algorithm that finds the position of the largest element in an array is called a cumulative algorithm.
false
The algorithm that prints elements separated by commas is called a cumulative algorithm.
false
The allocated size for the C-string char s1[1024] = "hello"; is 6 characters, while the effective size is 5 characters.
false
The member function int hours() const; provides read-write access to the hours property (however it is stored).
false
The release() function deletes the raw pointer that a unique_ptr contains, and then sets that pointer to a new value.
false
The statement new int[3]; allocates a single initialized integer on the heap.
false
Using public inheritance to derive Stack from vector is a good design because vector provides all of the capabilities that a Stack requires
false
When passing a 2D array to a function, the array parameter must explicitly list the size for all dimensions except for the last, like: void f(int a[3][], size_t n);
false
When removing an element from a partially-filled array, elements following the deletion position are shifted to the right.
false
With inheritance, the class you build upon is called a derived class in C++.
false
With inheritance, the class you build upon is called a superclass in C++.
false
With inheritance, the new class you create is called a base class in C++.
false
With inheritance, the new class you create is called a subclass in C++.
false
With inheritance, the new class you create is called a superclass in C++.
false
You may overload the conditional operator ?:.
false
Explain the output. Why is nothing printed? #include <iostream> using namespce std; int main() {cout << "Hello, World!"}
file not saved
A classification hierarchy represents an organization based on _____________ and _____________.
generalization and specialization
This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] != 0 && p[2] != 0) delete[] p; cout << p[0] / p[1] / p[2] << endl; }
has a dangling pointer
This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] == 0 || p[2] == 0) throw "Divide by 0"; cout << p[0] / p[1] / p[2] << endl; delete[] p; }
has a memory leak
A user-defined type created as a struct
has its implementation as its interface
The member function Mime::dance() is: class Performer { public: void dance() const; }; class Mime : public Performer { public: void dance() const; };
hidden or shadowed
This code illustrates the ___ idiom: auto n = 3; if (n % 2 == 1) n = -n; if (n < 0) n++; if (n % 2 = 0) n--;
independent if statements
_________________ is the Object-Oriented design feature that allows you to create a new class by using an existing class as a starting point, extending it to add new attributes and behaviors.
inheritance
What is the correct prototype for mystery? (It is not supposed to modify the array.) const int a[] = {2, 4, 6, 8}; cout << mystery(a, 4) << endl;
int mystery(const int *a, size_t n)
Which one of the following statements is the correct definition for a two-dimensional array of 20 rows and 2 columns of the type integer?
int num[20][2];
This complies, runs and prints 12. What is the correct parameter declaration for x?
int& x
in C++, the statement string s{3, 'X'};
is illegal; it does not compile
The variable *p: void f() { int *p = new int = {42}; }
is undefined. Code does not compile.
The variable p points to: void f() { int *p = new int[3] = {1, 2, 3}; }
is undefined. Code does not compile.
The variable *p: void f() { int *p = new int; }
is uninitialized
Below id the main function from the f2c program. Which line(s) uses the character input stream?
line 17
Below id the main function from the f2c program. Which line(s) contain a function call?
line 18
Look at the following piece of code. Check the answers that match it. (looks like a piece of paper}
machine dependent native code machine language
What command checks hw04 for correctness?
make test
When you create your own new, user-defined types, there are three different effective strategies you can use. Which of these is not one of those strategies?
modifying an existing class
This code illustrates the - idiom auto n = 3; if (n%2 == 1) n = -n; else if (n < 0) n++; else if (n % 2 = 0) n--; else n=0;
multiple selection
What type of member function is eat()? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; };
mutator
Examine the following UML diagram. Which of these data members or member functions are inherited but not directly accessible by the Student class?
name
Which member function(s) should not be overridden in Hobbit? class Creature { public: Creature(const string& name); virtual string name() const final; virtual string skills() const; virtual void addSkill(const string& skill); void print() const; }; class Hobbit : public Creature { . . . };
name(), print()
The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Examine the code shown. Which expression invokes the operator defined here? BigNum a{"12345.795"}, b{".95873421"}; const BigNum operator-() {...}
none of these
Below is a partially-filled array. When appending elements to this array in a loop, what statement(s) correctly updates the array with value? const size_t MAX = 100; double nums[MAX]; size_t size = 0; double value;
nums[size++] = value;
The variable p is located: void f() { int *p = new int; }
on the stack
Examine the following portion of code and then answer the questions that follow. -The variable p1 is created -Which line allocates a variable in the static storage area -Which line uses a dangling pointer? -Which line is a double delete?
on the stack None of these Line D Line E
The Time class represents the time of day on a clock. Examine the code shown. Which operator is called? Time t(8, 30, "a"); cout << t << endl;
ostream& operator<<(ostream&, const Time&);
To create the GiPod() from the Cadillac class, you should use.
private inheritance
In C++, the statement string s;
produces an empty string object
Below is a class hierarchy. Which assignment will fail to compile? class Pet { . . . }; class Puppy : public Pet { . . . }; class Kitty : public Pet { . . . }; class Ducky : public Pet { . . . }; Pet pet; Puppy pup; Kitty kit; Duck duck;
pup = pet;
Here is a class hierarcy for different card games. Using C++ terminology, the score() function is called a(n) ________________________________. The Hand Class
pure virtual function
Inheritance gives your programs the ability to express _______________ between classes.
relationships
In line 2, what is the receiver? 1. string {"happy"}; 2. auto pos = s.find('y');
s
Examine the class hierarchy below. Assume that both derived classes are concrete and completely defined. Which of the following member functions must be overridden in the derived classes? class Hand { std::vector<Card> cards; public: Hand() = default; virtual ~Hand() = default; void add(const Card&); virtual int score() const = 0; virtual void sort(); bool operator<(const Card& rhs) const; }; class PokerHand : public Hand { . . . } class BlackjackHand : public Hand { . . . }
score()
The ostream class is the/a ___________ class of istream.
sibling
Here is a class hierarchy for different card games. According to this design, which methods may the PokerHand and BlackjackHand use without making any changes? There may be more than one correct answer.
sort() add() get()
The ___________ of an object consist of its attributes or characteristics, represented by the values stored in its data members.
state
Examine the following code and then answer the questions: the duration of the variable a is: the linkage of the variable c is: the scope of the variable v is: the duration of the variable d is:
static none block automatic
Where are the characters "Goodbye" stored in memory? char s1[1024] = "Hello"; void f() { const char *s2 = "Goodbye"; char s3[] = "CS 150"; }
static storage area (read-only)
The variable *p: void f() { int *p = new int{42}; }
stores the value 42 in C++11 only
The variable *p: void f() { int *p = new int(42); }
stores the value 42 in all versions of C++
Assuming that you are not implementing a portion of the standard library, which of these are legal identifiers.
string _int Switch
Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum = 0; for (auto e : a) sum += e; cout << "sum->" << sum << endl;
sum->20
What kind of error is this?main.cpp:31:49: error: expected ';' after expression
syntax error
The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } const Point operator++(int n) { Point temp(*this); . . . return ________________; } };
temp
The variable p points to: void f() { int *p = new int[42](); }
the first element of an array of 42 ints with the value 0
The variable p points to: void f() { int *p = new int[42]; }
the first element of an array of 42 uninitialized ints
The variable p points to: void f() { int *p = new int[42]; }
the first element of an array of 42 uninitialized ints
A class represents a template or blueprint for creating objects of a particular kind.
true
A shared_ptr uses a reference count to manage how many pointers point to an object.
true
Accessor member functions should always end in the keyword const.
true
An abstract class is a class that contains member functions that are specified but not implemented.
true
An abstract class requires its concrete derived classes to override all of its pure virtual (abstract) member functions.
true
Arrays generally have higher performance than a vector.
true
Before passing an array to a function, sizeof(a)/sizeof(a[0]) will tell the number of elements in the array.
true
Consider the Shape class hierarchy, along with Circle, Square and Star from your text. The Circle class is a concrete class.
true
Creating a new class by combining instances of simpler classes as data members is called composition.
true
Encapsulation enforces the principle of data hiding.
true
If a member function is in the private section of a class, it can only be called by other member functions of the class.
true
If a virtual member function does not use the keyword final, then any derived class may override that function.
true
If the new operator cannot allocate memory, C++ throws an exception.
true
In a constructor, initializing data members by using the assignment operator means that those objects may be initialized twice.
true
In a partially-filled array size represents the number of elements that are in use.
true
Overloaded operators may be implemented as non-member functions.
true
The C++ facility that allows a derived class to have multiple base classes is known as multiple inheritance.
true
The allocated size for the C-string char s1[1024] = "hello"; is 1024 characters, while the effective size is 5 characters.
true
The characters for the C-string char s1[] = "hello"; are stored in user memory and may be modified.
true
The iostream class in the C++ standard library uses multiple inheritance
true
The parameter declarations int *p and int p[] mean the same thing.
true
The reset() function deletes the raw pointer that a unique_ptr contains, and then sets that pointer to a new value.
true
The statement new int; allocates an uninitialized integer on the heap.
true
To allocate memory on the heap, C++ uses the new operator.
true
With inheritance, the class you build upon is called a base class in C++.
true
You may create a reference to a class that is abstract.
true
You may not overload the member-selection (or dot) operator.
true
You may not overload the scope operator ::.
true
What is printed here? #include <iostream> using namespace std; int main() { int n = 6;cout << n++ << n++ << n++ << endl; }
undefined
Above is is a class hierarchy for different card games. Assuming that these are the only classes and that the concrete classes are correctly completed, which of the following non-member functions are polymorphic? More than one answer may be correct.
void draw(Hand& h) const { ... } void draw(Hand* h) const { ... }
Below is a class hierarchy for card games. Assuming that these are the only classes and that the concrete classes are correctly completed, which of the following non-member functions are polymorphic? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; virtual int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . };
void draw(const Hand& h) { . . . }
Below is a class hierarchy for card games. Assuming that these are the only classes and that the concrete classes are correctly completed, which of the following non-member functions are polymorphic? class Hand { std::vector<Card> cards; public: void add(const Card&); Card get(size_t index) const; virtual int score() const; }; class PokerHand : public Hand { . . . }; class BlackjackHand : public Hand { . . . }; class GoFishHand : public Hand { . . . };
void draw(const Hand* h) { . . . }
This compiles, runs and prints 5,4. What is the correct prototype? int a = 4, b = 5; swap(a, b); cout << a << "," << b << endl;
void swap(int& a, int& b);
Below is a partially-filled array. If you are appending elements to this array in a loop, what is the correct loop bounds condition? const size_t MAX = 100; double nums[MAX]; size_t size = 0;
while (size < MAX) . . .