Computer Science II - Midterm Practice

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Show how to obtain the address of a scalar (i.e. not array) variable.

"&" - ampersand

Show how to obtain a pointer variable.

*p1

• Assume the following class definition: #ifndef DATE_H #define DATE_H #include <iostream> using std::ostream; using std::istream; class Date { friend ostream & operator<<(ostream &, const Date &); //overloading output stream operator friend istream & operator>>(istream &, Date &); //overloading input stream operator public : Date ( ); Date (int, int, int); ~Date( ); int getMonth() const; int getDay() const; int getYear() const; void setMonth(int); void setDay(int); void setYear(int); private: int month; int day; int year; }; #endif 2) Why are these functions declared to return a reference of ostream or istream respectively?

- A reference to the stream is returned to facilitate chaining operations.

Which statement is false about templates? • Using the prefix template<class T> defines a template that can only be used on a class type argument. • Calling a template function does not require explicitly passing in the type. • A template function that assigns into a variable of the parameterized type cannot be used with a static array. • One an object is declared using a template, the object can be used without explicitly referencing the parameterized type.

- A: Using the prefix template<class T> defines a template that can only be used on a class type argument. {Could be any type, the word class is part of the template syntax and doesn't impose type restrictions.}

Which statement regarding inheritance is false? • Derived classes inherit all data members and member functions regardless of ability to access them. • A member function that is defined virtual can return a different type than its parent definition. • A child object can be assigned to a variable of type parent and refer to the child data members as long as there are virtual member functions. • A parent reference variable can access child members if they are used in overridden functions that were defined to be virtual in the parent.

- C: A child object can be assigned to a variable of type parent and refer to the child data members as long as there are virtual member functions {Parent can only access child members in function declared to be virtual in the parent that are overridden in the child.}

Which of the following statements will not produce a syntax error? • Defining a const member function that modifies a data member of the object. • Invoking a non-const member function on a const object. • Declaring an object to be const. • Declaring a constructor to be const.

- C: Declaring an object to be const

Which of the following statements will produce a syntax error? • Accessing a static member function using a handle (i.e. reference or pointer) to the user defined object. • Directly accessing a static data member defined in the public interface using a handle to the user defined object. • Directly accessing a static data member defined in the private interface of the class using a handle to the user defined object. • Directly accessing a data member defined in the private interface of the class in a class member function without a handle to the user defined object.

- C: Directly accessing a static data member defined in the private interface of the class using a handle to the user defined object

An overloaded + operator takes a class object and a double as operands. For it to be commutative (i.e. a + b and b + a both work): • Operator+ must be a member function of the class from which the objects are instantiated. • Operator+ must be a non-member function. • It must be overloaded twice; a member function that takes the object as the left operand and a global function that takes two arguments. • The + operator cannot be overloaded to be commutative.

- C: It must be overloaded twice; a member function that takes the object as the left operand and a global function that takes two arguments {A better way to solve it is to provide a constructor that takes a double and create an instance of the object.}

What happens if no constructor is defined?

- Constructors are automatically assigned so, nothing happens.

Which of the following statements is false? • You can access static variables without instantiating an object on the class that defines them. • Constant variables declared static can be initialized as private data members. • Constant variables can be initialized in the body of the constructor. • Static variables can be initialized in the member initialize list of a constructor.

- D: Static variables can be initialized in the member initialize list of a constructor

The stream insertion operator << and the stream extraction operator >> are automatically overloaded by the system to handle all data types - including strings and all user defined data types.

- False

A default constructor is a constructor that must receive arguments which are used to initialize the data members of a class.

- False A default constructor either has no parameters or has a default value for every parameter, meaning that no arguments are passed to the default constructor.

A reference to a parent class that is assigned to a child object can access all of the child's public member functions.

- False A reference to a parent class can only reference child functions that are in the virtual table for the parent class.

Given the following constructor for class Increment, based on its' initialization we can assume that the variable incrementVar is a static variable. Increment::Increment(int c, int i ) : incrementVar( i ) { countVar = c; }

- False A static variable cannot be initialized in an initializer list of a constructor. The initializer list is reserved for base class constructors and initializing object data members.

Assume y and z are user-defined objects of the same class and the += operator is an overloaded member function, such that y+=z adds z and y, then stores the results in y. The expression y += z is equivalent to z.operator+=( y ).

- False Actually, it is y.operator+=(z). The left-hand side is the invoking object.

A class that manages an array of objects needs a destructor to free the memory for the array.

- False Static arrays do not require a destructor. Only dynamic arrays do. The statement didn't specify.

Operator overloading can be used to overload any C++ operator so long as the definition of that operator is not changed.

- False There are a couple of operators that cannot be overloaded: *, ., & and ?:

#include <iostream> using std::ostream; using std::istream; class Date { friend ostream & operator<<(ostream &, const Date &); //overloading output stream operator friend istream & operator>>(istream &, Date &); //overloading input stream operator ... }; 1) Why are the istream and ostream overloaded functions declared as friend?

- Friend functions have access to private members. It is more efficient to access members directly than to use accessor functions. If a change is made, the function needs to be re-implemented so there is no advantage to using accessor functions.

____ ____ ____ must be defined for a class to be considered an abstract class.

- Pure virtual functions

What are 3 characteristics of constructors?

- Same name as class - Used to initialize member - No return type - Can be overloaded

#ifndef DATE_H #define DATE_H #include <iostream> using std::ostream; using std::istream; class Date { friend ostream & operator<<(ostream &, const Date &); //overloading output stream operator friend istream & operator>>(istream &, Date &); //overloading input stream operator public : Date ( ); Date (int, int, int); ~Date( ); int getMonth() const; int getDay() const; int getYear() const; void setMonth(int); void setDay(int); void setYear(int); private: int month; int day; int year; }; #endif 3) Why are these functions declared as global functions and not as class member functions?

- The overloaded operators for istream and ostream are required as friend because the invoking object is the stream, not the current object.

Constructors and Destructors of a class are called automatically, even if they are not explicitly defined in the class.

- True

Objects instantiated for a particular class get their own copy of each non-static data member variable defined for that class - regardless of type.

- True

A class scope variable hidden by a block-scope variable can be accessed by preceding the variable name with the scope resolution operator :: .

- True A block-scope is anything between { statements }. Variables defined in a block hide variables of the same name defined outside of that block. If the variable has a class scope, the scope resolution operator :: can help access a hidden variable.

One reason we may want to return a reference to an object of a specified class using the this pointer (e.g. *this) from within a class member function is to facilitate operator overloading.

- True A reference to *this is returned to facilitate operation chaining which is commonly done with C++ operators. In that way it facilitates operator overloading.

When object composition is used (e.g. a class definition has as a data member an object of another class), the member objects are constructed first, in the order they are declared in the host's class.

- True The order that objects are created and initialized is to go up the hierarchy to the top of the leftmost class and initialize construct/initialize data members from top to bottom. When multiple inheritance is used, the traversal goes in left to right order.

Class members declared as being ____ are accessible only to member functions of the class and friends of the class.

- private

If a child inherits the parent object using ____ inheritance, then the grandchild can see all ____ and ____ data members but the outside world cannot.

- protected - public - protected

The member functions and data members that are in the ____ domain of the class are referred to as the ____ of the class.

- public - interface

A ____ ____ member is declared in the class and initialized immediately when defined outside of a class in the global space.

- static const

There are at least five major errors in the following code segment; identify them and explain how to correct them. #include <iostream> using namespace std; class Example { public: void Example(); void Example( int y = 10 ) : data( y ) {} int getIncrementedData() const { data++; return( data ); } static int getCount() { cout << "Data is " << data << endl; return( count++ ); } private: int data; static int count = 5; }

// Constructors do not have a type (void should not be there) // Only 1 default constructor per class. // No return type for a constructor. // Incorrect const declaration (data++). // Cannot access object member in static function // Cannot initialize static member in class declaration // Missing semi-colon

Exactly what is the output when the following program executes: #include <iostream> using namespace std; class ScopeClass { public: ScopeClass() { cout << "Default Constructor" << endl; } ScopeClass(int v) { cout << "Constructing object with numOfInstances == " << numOfInstances << " and var == " << var << endl; numOfInstances++; var = v; } static int getInstance() { return( numOfInstances ); } int getVar() { return( var ); } private: int var; static int numOfInstances; }; int ScopeClass::numOfInstance; int main() { cout << "Declaring an array of 5 scope class objects..." << endl; ScopeClass as[5]; cout << "Instantiating object s..." << endl; ScopeClass s; cout << "Number of Instances == " << s.getInstance() << " Var == " << s.getVar() << endl; cout << "Instantiating object s1..." << endl; ScopeClass s1(1); cout << "Number of Instances == " << s1.getInstance() << " Var == " << s1.getVar() << endl; cout << "Instantiating object s2..." << endl; ScopeClass s2(2); cout << "Number of Instances == " << s2.getInstance() << " Var == " << s2.getVar() << endl; }

// Var is printed before it is initialized, it is garbage. // Static class member variables are initialized to 0 (or whatever means 0, default constructor) if left uninitialized. Declaring an array of 5 instances of Scope Default Constructor Default Constructor Default Constructor Default Constructor Default Constructor Instantiating object s Default Constructor Number of Instances == 0 Var == 0 Instantiating object s1 Constructor object of numOfInstances == 0 and var == 4197133 Number of Instances == 1 Var == 1 Instantiating object s1 Constructor object of numOfInstances == 1 and var == 0 Number of Instances == 2 Var == 0

A pointer to an *int* requires less memory than a pointer on a double.

False

Assuming we know the machine architecture, a pointer's size is known if the type is known.

False

Automatic variables are automatically assigned a value when declared.

False

Memory for a variable declared in main is globally available to the entire program.

False

When passing a multidimensional array into a function, empty square brackets can be used to avoid specifying the dimensions. e.g. void fillArray(array[], int size1, int size2);

False Only the first one can be empty.

• Write the specified code #1) Write the class definition for an Employee class that contain the following data member definitions: • term-57static const double minWage = 5.75; • static const int MAXID = 15; #2) As well as declarations for data members: • employee_id - character array of length MAXID • first name - string • last name - string • hours worked - double • hourly rate - constant double #3) Include in the class definition: • all the data member definitions and declarations • a default constructor that initializes the data members as necessary to an appropriate default. Note: The default for the hourly rate should be the minWage. • a constructor that accepts arguments to initialize the data members. This constructor should initialize each data member to the appropriate parameter passed to it.

Note: Assume that the call is made in the driver program and that the mutator member function setMinWage is declared to be static. class Employee { public: // Constructors Employee(); Employee(string fname, string lname, char *id, double rate, int hours); private: // class data members for Employee // Minimum wage and default: static const double MinWage; // Maximum length of ID: static const int MAXID; // Gross pay is the pay that is received based on hours worked and hourly wage. double grossPay() const { return hours_worked * hourly_wage; }; // Two employees are equal if their gross pay is equal friend bool operator==(const Employee& e1, const Employee& e2); // object data members for Employee // character array MAXID+` length char *employee_id; string first_name; string last_name; // Must be minWage or greater double hourly_rate; // Must be 0 or greater. int hours_worked; }; // Define static variables in class definition const double Employee::MinWage = 5.75; const int Employee::MAXID=15; Employee::Employee() : first_name(""), last_name(""), hourly_rate(minWage), hours_worked(0) { employee_id = new char[MAXID+1]; employee_id[0] = '\0'; } Employee::Employee(string fname, string lname, char *id, double rate, int hours) : first_name(fname), last_name(lname), hourly_rate(rate), hours_worked(hours) { if (strlen(id) > MAXID) { cout << "Invalid Employee ID: must be fewer characters than" << (MAXID+1) << endl; exit(1); } strcpy(employee_id, id); } bool operator==(const Employee& e1, const Employee& e2) { return e1.grossPay() == e2.grossPay(); }

Explain the order of construction in an inheritance hierarchy and the order of destruction. When does a composite object get created?

Objects are constructor from the root of the hierarchy (greatest ancestor) on down. Objects are destructed in the reverse order of how they are constructed. A component object that is part of another object gets created after all ancestors in the object hierarchy are created but before the object constructor executes. All components must be available for initialization in the initialization section. Thus the components exist before the constructor actually runs.

• State the protype and function definition required to: // Declared as a non-member friend bool operator==(const Date& d1, const Date& d2); // Declared as member function bool operator==(const Date& date);

Overload the equality operator to check equality of two date objects (e.g. d1 == d2) where d1 and d2 are both instantiated objects of class date.

• State the protype and function definition required to: // As non-member function bool operator==(const Date& d1, const Date& d2) { return d1.day == d2.day && d1.month == d2.month && d1.year == d2.year; } // As a member function bool Date::operator=(const Dateterm-55& date) { return date.day == day && date.month == month && date.year == year; }

Overload the equality operator to check if the year of a date object is equivalent to some specified year (e.g. year == d1) where year is an integer variable and d1 is an object of class date. - In class declaration: friend bool operator==(const Date& date, int year); - In class.cpp definition: bool operator==(const Date& date, int year) { return date.year == year; }

Explain when an operator overloaded function can be implemented as a member function and when it should be implemented as a global function. Be specific.

Overloaded operators have to be implemented as global non-member (friend) functions when the invoking object is not a member of the class. The first parameter is the invoking object and if it is not a parameter of the current class, then it has to be should be defined as a global non-member function. Overloaded operators must have at least 1 class parameter. When implementing them, if a built-in type is a parameter, it must be implemented as a non-member (friend) function so that 1 parameter is a class. If the operator has to return a reference to the invoking object and that object is a member of the current class, it is usually best to implement as a member function.

//reverse call swap Complete function: void reverse(int array[], int size) { for(int i = 0; i < size/2; i++) { } }

REVERSE SWAP function: { int value = size/2; array[size] = value; swap(&array[i], &array[size - i - 1]) cout << array[size] << endl; }

//swap two integers using pointers Complete function: void swap(int *val1, int *val2) { int temp; }

SWAP function: { temp = *val1; *val1 = *val2; *val2 = temp; }

What are 3 similarities and differences between structs and classes?

Similarities: - "Public" section - Serve as "type" declaration - Can use assignment operator - Can use member functions Difference: - Classes have a private section - Structs are public by default.

What happens when you assign a struct object to another of the same type?

The values on the initial struct are copied into the new struct exactly as they were.

A pointer to a *char* can point to either a single char variable or an array of chars.

True

All variables have a type that dictates the size in bytes and the range of values.

True

You can declare a static array of any type including built-in and user-defined types.

True

When declaring a static array, the size can be given either explicitly with an integer variable or implicitly with an initializer.

True const int a[5] OR int a[] = {1,2,3}

What do you need to know to correctly dereference the pointer in memory?

You need the * to know that it is initialized.

Write a statement that declares an array variable named intPtrArray that can store 10 pointers to int.

const int VARIABLES = 10; int *intPtrArray[VARIABLES];

Class members are accessed via the ____ or ____ operator in conjunction with a handle of an object of the class.

dot or ->

MAX function:

double findIndexOfMaxInArray(double myArray[], int myArraySize) { int largestSoFar = 0; int indexOfLargest = -1; for(int index=0; index < myArraySize; index++) { if(myArray[index] > largestSoFar) { largestSoFar = myArray[index]; indexOfLargest = index; } } return(indexOfLargest); }

MIN function:

double findIndexOfMinInArray(double myArray[], int myArraySize) { int smallestSoFar = 100; int indexOfSmallest = -1; for(int index=0; index < myArraySize; index++) { if(myArray[index] < smallestSoFar) { smallestSoFar = myArray[index]; indexOfSmallest = index; } } return(indexOfSmallest); }

Write a loop to read up to 15 int values and store them into array a. Stop reading if the user enters -999 or the array is full. const int CAPACITY = 16; int a[CAPACITY]; cout << "Enter up to 15 positive integers, enter -999 to end when you are done. \n"; Complete program:

for(int i = 0; i < CAPACITY; i++) { int user_Value = a[CAPACITY]; cin >> user_Value; if( (user_Value != -999) && (i < (CAPACITY-1)) ) break; } //To store -999 to the ens of array: a[15] = -999; a[i] = -999;


Kaugnay na mga set ng pag-aaral

Immune sys---Lupus, arthr/connect IGGY 20, Chapter 18 Iggy Practice Questions, Chapter 46 10th edition, Brunner Chapter 39, Musculoskeletal Trauma

View Set

domain quiz - lifespace development

View Set

Chapter 4: Understanding Food and Nutrition Labels

View Set

Unit 8: Global Atmospheric Change

View Set

الوحدة الأولى: المقدمة والمخالفات المرورية والنقاط المرورية

View Set

castillo mid term multiple choice and fill in the blanks

View Set

EXAM 2 Chapter 51: Assessment and Management of Patients with Diabetes Prep-U, EXAM 2 Adult Prep U CH 51 Assessment and Management of Patients With Diabetes part 2

View Set