Absolute C++ 5th Edition by Walter Savitch – Test Bank

$20.00

Category:

Description

INSTANT DOWNLOAD WITH ANSWERS

Absolute C++ 5th Edition by Walter Savitch – Test Bank

Chapter 6 – Structures and Classes  Test Questions

 

These test questions are fill in the blank, multiple choice, and true false.  The multiple-choice questions may have more than one correct answer. There is one matching question. Mark all of the correct answers for full credit. True/false questions require an explanation in addition to the true/false response. If the response is false, a correction is required.

True False:

Comment required.

  1. A C++ structure, or struct, like the C++ array, is a homogeneous data structure. (i.e., all data is of the same type)

Answer: False

Explanation: The struct provides a mechanism to define a collection of values that may be of several different types.

  1. Structure definitions are usually global (defined outside any functions).

Answer: True

Explanation: A structure definition is a type that, like const definitions, we usually want to be available everywhere in a program that follows the structure definition.

  1. A structure member is access using the index operator [ ], with the member name as index. [ ]

Answer: False

Explanation: Access to structure members is made by giving the structure tag, followed by a dot followed by the member name.

Example: Given the structure definition and variable definition such as

struct CDAccount

{

double balance,

double interestRate;

int term;

};

CDAccount account1;

Access to member variables of account1 may be had using the dot operator:

account1.balance1

account1.interestRate

  1. A structure variable can be defined directly in the same statement that defines a structure definition.

Answer: True

Explanation: The variables s and t are structure variables of structure type myStruct under the following definitions:

struct myStruct

{

int i;

double d;

} s, t;

  1. The following definition of the structure variables of type myStruct s and t could be made using several definitions using the structure tag.

struct myStruct

{

int i;

double d;

} s, t;

Answer: True

Explanation: This possibility is why the semicolon is necessary at the end of a structure definition. Here is how the definitions may be rewritten.

struct myStruct

{

int i;

double d;

};

myStruct s;

myStruct t;

  1. A structure can have a member whose type is another structure.

Answer: True

Explanation: Structures collect, name and give a type to related data. A subcollection of data from a structure may be so closely related that we want to make a struct of the subcollection. Example: A struct containing personal data may contain a birth date of struct type, in turn composed of day, month and year.

  1. Consider these hierarchical structures.

struct Date

{

int year;

//members

};

struct Person

{

Date birthDay;

//other members

};

Person Bill;

The year of Bill’s birthday may be accessed as Bill.year;

Answer: False.

Explanation: To access the year of Bill’s birthday one must specify the Person’s Date structure variable, as Bill.birthDay.year.

  1. No special syntax is necessary to define a function that uses a structure parameter. (This is unlike using an array parameter.)

Answer: True

Explanation: Once the structure definition has been made, a structure tag is a type that may be used in any way that a built-in type such as int or double can be used. For example, given the structure definition

struct S {/*…*/};

here is a definition of the void function func that has an S structure parameter.

void func(S y);
This is unlike using an array parameter, which requires square brackets, as well as an additional size parameter, such as

void bar(Y[] x, int size);

 

  1. There is no aggregate initialization available for structure variables. You must declare structure variables then use assignment to initialize the members.

Answer: False

Explanation: A struct can be initialized by using a sequenced of initializers very much like arrays.

struct A { int a; int b; double d;}; A x = { 1, 2, 3.0};

  1. A class is a type similar to a structure type that normally has member functions as well as member variables.

Answer: True

Explanation: We have treated the structure as a data members only aggregate, as C does, and we treat the class as having function members and data members.

  1. Consider the class and struct definitions below.

struct myStruct

{

int i;

double d;

};

class myClass

{

int i;

double d;

};

myStruct a;

a.i = 3;

myClass b;

b.i = 3;

True or False: All these statements will compile with no problem.

Answer: False

Explanation: The access for class defaults to private. When compiling this code one compiler warns: and another warns in addition that:

cpp 17: ‘myClass::i’ is not accessible in function main()

Another compiler warns in addition that all members of class myClass are private. The code b.i = 3; attempts to access a private member of myClass, and will cause the compiler to issue an error message.

 

  1. The concept of class is central to Object Oriented Programming.

Answer: True

Explanation: The class concept supports OOP. Object oriented programming (OOP) is a powerful technique that divides problems by who is acting in a problem (actors are the class type objects) and what they are doing (these are the member functions.)

  1. A class type cannot be used in some ways that a built-in type can be used.

Answer: False

Explanation: A class is a type just like an int or a double. You have variables or function parameters of class type. You can return a class object from a function. You can treat a class just like any other type.

  1. In defining a member function whose declaration is in a class, you use the dot operator to specify that the member function being defined belongs in the class, as

class foo

{

public:

// other members

void output( );

// other members

};

 

void foo.output( )

{

/* whatever */

}

Answer: False.

Explanation: This is a mistake that students who have studied Java may make. Nevertheless, it occurs among all groups of students. C++ uses the scope resolution operator when we are specifying what class a member is from, and a dot operator to specify the calling object. The correct syntax for this function definition follows. Note carefully the use of the scope resolution operator, ::to specify that output is being defined in the scope of  class foo.

void foo::output( )

{

/* whatever */

}

 

  1. If, in a class, one uses the keyword public:, it affects only the member that immediately follows the keyword public, making this member accessible to any other function defined anywhere.

Answer: False

Explanation: The effect of the public: keyword is from the keyword to the next private: keyword, so there is a region where anything that is there defined is public, not just a single member. The  remark about access is correct.

  1. There is no access to private members of a class by any function defined outside the class.

Answer: True.

Explanation: In a class, the all members defined after a keyword private: and before the next public: keyword are called private members. Access to private members by functions defined outside the class is prohibited. (Note: This ignores the issue of friend functions, which will be treated in a later chapter.)

  1. A data type is a collection of a set of values together with a set of basic operations defined on the values.

Answer: True

Explanation: Examples of a data type are int with +_*/% and other operations, double with +_*/.

  1. An abstract data type is a collection of a set of values together with a set of basic operations defined on the values.

Answer: false

Explanation: To qualify as an abstract data type, a data type must conceal the details of how the operations and values are implemented. The operations should be sufficiently documented that one can use them without knowing the implementation.

  1. Multiple public: and private: sections are prohibited in a class.

Answer: False

Explanation: The keywords public: and private: have effect that runs up to the next instance of one of these keywords. There is no prohibition against having a sequence of private section after a public section and so on.

  1. A sure test of whether you have succeeded in producing an Abstract Data Type (whether you have truly separated the interface from the implementation) is whether you can use the ADT then change either the implementation or the client code without being required to change the other.

Answer: True

Explanation: This is the definition of ADT.

  1. The scope resolution operator can be used with an object to qualify a member function.

Answer: False

Explanation: The scope resolution operator is used with a class name to qualify a member to tell the compiler that this member comes from that class.

  1. The dot operator is used between an object and a data member or between a calling object and a call to a member function from the class of the object.

Answer: True

Explanation: If we have object.func(arg_list) we speak of the object as the calling object for the function call func(arg_list). The dot is the operator that signals to the compiler that we intend to call that function, with data members available from the object. If the object.data_member is specified, the dot says to the compiler that we want to access the data from data_member that belongs to that particular object.

 

Multiple Choice
  1. C++ allows the programmer to deal with data at a higher level of abstraction in part because related data of differing types can be treated as a unit in
    1. a array variable
    2. a structure variable
    3. a function
    4. a library
    5. a class variable

Answer:

  1. b) structure variable. and e) a class variable

Explanation: Arrays are homogeneous, functions do not encapsulate data, and  we know that libraries are collections of functions organized for easy access. The ones that are left, class and struct types, allow heterogeneous data as a unit is a structure or class variable.

 

  1. A member of a structure or of a class is accessed using the
    1. Comma operator
    2. The dot operator
    3. The indexing operator
    4. The ampersand operator

Answer:

  1. b) the dot operator

Explanation: The member of a structures or classes are accessed by writing the tag followed by the dot operator which in turn is followed by the name of the member or a call to a member function.

 

  1. What is the error in the following structure definition?

struct A

{

int b;

int c;

}

int main()

{

A x;

// other code

}

Answer:

The terminating semicolon is missing from the definition of struct A. Error messages for this may be clear “Semicolon missing from structure or class definition.” However, one compiler says cryptically, “Too many types in declaration.”

  1. Here are several different initializations of a structure variable. State what happens in each initialization.

struct WeatherData

{

int temperature;

int windChill;

int windSpeed;

};

  1. WeatherData prediction ={ };
  2. WeatherData prediction ={40};
  3. WeatherData prediction ={40, -10, };
  4. x WeatherData prediction ={40, -10, 20 };

Answer:

  1. All the structure members are set to 0.
  2. temperature is set to 40, the other two variables are set to zero.
  3. temperature is set to 40, windChill is set to –10, and windSpeed is set to 0
  4. temperature is set to 40, windChill is set to –10, and windSpeed is set to 20

Explanation: If there is an initializer list and a member is missing an initializer, that member is set to a zero appropriate to the type. a) The issue here is whether the empty initializer list is allowed. They are permitted for structs (but not for arrays), so all the structure members are set to 0. For b) and c), the members missing initializers are set to 0. In d), all members are set to the corresponding member of the initializer list.

  1. Given the program, which of the following class member accesses are legal?

#include <iostream>

using namespace std;

class DayOfYear

{

public:

void input();

void output();

// other public members

private:

int month;

int day;

// other private members

};

int main()

{

DayOfYear birthDay;

birthDay.input();          // a)

birthDay.day = 25;         // b)

cout << birthDay.month;    // c)

cout << birthDay.output(); // d)

if(birthDay.month == 1)    // e)

cout << “Januaryn”;

}

Answer: Actual compiler error messages follow:

Error b): ‘DayOfYear::day’ is not

accessible in function main()

Error c): ‘DayOfYear::month’ is not

accessible in function main()

Error e): ‘DayOfYear::month’ is not

accessible in function main()

Explanation:  The declaration of birthDay as a DayOfYear object is OK.  a) and d) are accesses to a public input and output functions. b) attempts to write a private member, c) and e) attempt to fetch a value from a private member month. In d), output is public, so d) is OK

  1. Which of the following terms are used to describe defining a class so that the implementation of the member functions is either not known or at least is irrelevant to its use
    1. walling up
    2. encapsulation
    3. abstraction
    4. Caging up the data and functions
    5. Information hiding

Answer: The terms used in the text are b) c) and e).

Explanation: Each of these terms mean that the details of the implementation of the functions is hidden from the client programmer (the programmer who uses the class). The text prefers encapsulation.

  1. Given the program, which of the following class member accesses are legal?

#include <iostream>

using namespace std;

class DayOfYear

{

public:

void input();

void output();

int month;

int day;

};

int main()

{

DayOfYear birthDay;

birthDay.input();          // a)

birthDay.day = 25;         // b)

cout << birthDay.month;    // c)

cout << birthDay.output(); // d)

if(birthDay.month == 1)    // e)

cout << “Januaryn”;

}

Answer: All of them are legal. Everything is pubic now, so any function can access any member .

  1. When you define a C++ class so that the result is an ADT, which of the following remarks about whether to make a member variable or function public or private are correct?
    1. Make them all public. It simplifies life and makes things more efficient to be able access members anywhere.
    2. Don’t make member variables public.
    3. Make all member functions public.
    4. There are some member functions that shouldn’t be public, but most should be public.

Answer: Probably b) is correct, see Explanations. d) is correct.

Explanation:

If you follow a) you are not encapsulating anything. You won’t have an ADT if you do this. b) is likely to be a good rule to follow. c) is too restrictive. There are helper functions, or as the text calls them, auxiliary functions that help member functions do their job that should not be public, but most member functions should be public, and member variables private.

  1. When you define a C++ class, which of the following should be part of the implementation?
    1. all declarations of private member variables
    2. all declarations for public member functions
    3. all explanatory comments for public member declarations.
    4. all declarations for private member functions (auxiliary or helping functions)
    5. all member function definitions, public and private (implementations of functions).

Answer: a) d) and e)  are implementation.

Explanation: b) c) are interface. This is information needed to know what the class and its member do, but nothing that tells how the do “it”. The following are implementation:  a) private member variables are part of the implementation, not the interface. d) Private member functions are part of the implementation not of the interface e) definitions of functions are part of the implementation not interface.

  1. When you defined a C++ class, which of the following should be part of the interface?
    1. all declarations of private member variables
    2. all declarations for public member functions
    3. all explanatory comments for public member declarations.
    4. all declarations for private member functions
    5. all member function definitions (public or private)

Answer: b) c)

Explanation: The public member function declarations and commentary should be sufficient to use the class.

 

Free Form Questions:
  1. In the structure definition

struct StudentRecord

{

int studentID;

char grade;

}

give the structure tag, and each of the member names.

Answer:

The structure tag is StudentRecord. The structure member names and types are studentID of type int, and grade, of type char.

 

  1. Given the structure type and variable definitions

struct ShoeSize

{

char width;

int number;

};

struct ShoeType

{

char style;

ShoeSize size;

double price;

};

ShoeType shoe1, shod2;

What type do these variables have?

  1. style
  2. size
  3. size.width
  4. price
  5. size.number

Answer: a) char, b) ShoeSize, c) char, d) double, e) int.

Explanation: a) The type of the style member in struct ShoeType is char. b) The type of the size member of struct ShoeType is ShoeSize. c) The member shoe1.size has type ShoeType, the width member of ShoeType has type char. d) The member shoe1.size has type ShoeType, the number member of ShoeType has type int.

  1. What is the output of the following program.?

#include <iostream>

using namespace std;

struct ShoeType

{

char style;

double price;

};

int main()

{

ShoeType shoe1, shoe2;

shoe1.style = ‘P’;

shoe1.price = 98.98;

cout << shoe1.style << ”  $” << shoe1.price << endl;

shoe2 = shoe1;

//Put shoe2 on sale!

shoe2.price = shoe1.price/2;

cout << shoe2.style << ”  $” << shoe2.price << endl;

}

Answer:

P  $98.98

P  $49.49

Explanation: Structure variables are used as variables in an expression just like any other variable.

 

  1. Write a definition for a structure type for personnel records for hourly employees. The record contains an hourly wage rate, accrued vacation in an integer number of days, and employee status (use ‘T’ for temporary and ‘P’ for permanent). Part of the problem is appropriate choices of type and member names.

Answer:

struct HourlyEmployee

{

double wageRate;

int accruedVacation;

char status; // ‘P’ for permanent, ‘T’ for temporary

};

Explanation:

The name, HourlyEmployee reflects the fact that this is an employee record for an hourly employee. Member names should reflect the meaning of the member variable. Regarding the comment on the status line: the values for status are mnemonic, nevertheless, it may be better not to depend on memory too much.

  1. Given the ShoeType structure type definition, write a function declaration (prototype) for a void function that uses a ShoeType structure variable as a value parameter.

struct ShoeType

{

char style;

double price;

};

Answer: void useShoeRecord(ShoeRecord myShoe);

Explanation: A structure type can be used exactly as any other type.

 

  1. Given the ShoeType structure type-definition.Write a function for the declaration (prototype).

struct ShoeType

{

char style;

double price;

};

void setSalePrice(ShoeType& Item, double discountRate);

//discountRate =(discounted price)/(regular price)

//Adjusts sale price to reflect the specified discount.

Answer:

void setSalePrice(ShoeType& Item, double discountRate)

{

Item.price = Item.price * discountRate;

}

Explanation: Use of reference parameter causes changes inside the function  to be reflected outside.

  1. Given the ShoeType structure type definition. Write a function for the declaration (prototype).

struct ShoeType

{

char style;

double price;

};

void readShoeRecord(ShoeType& Item);

// Prompts for data and fills ShoeType argument members

Answer:

void readShoeRecord(ShoeType& Item)

{

cout << “Enter style, one character, then press <CR> “;

cin >> Item.style;

cout << “Enter price as 66.66, (with decimal, no $)”

<< “then press <CR> “

cin >> Item.price;

}

Explanation: Use of reference parameter causes changes inside the function  to be reflected outside.

  1. Carefully distinguish between the scope resolution operator, and the dot operator.

Answer:

Both the dot operator and the scope resolution operator are used with data and function member names of a class or struct to specify of what class/struct the member name is a member. The dot operator is used with an object to qualify a data member name or with a call to function member. The scope resolution operator is used with the definition of member function to tell the compiler that this function is the one declared in the specified class.

  1. Carefully define mutator and accessor functions of a class.

Answer:

A mutator function allows the class author to control changes to class data, even filtering out bad data. An accessor function allows the class author to control access to class data and the format of the presentation.

  1. It seems that mutator and accessor functions defeat the purpose of making the member variables private. Why is this not so?

Answer:

The mutator functions can filter data and control the way data members are set. For example, you (as class author) can exclude illegal data. With accessor functions you (as class author) can allow the client to see just the variables you want seen, in the format in which you want them seen.

  1. Carefully identify, define each term and give differences between the implementation and the interface of an abstract data type (ADT). This requires a bit more writing of English than other question on this test.

Answer:

The interface consists of two sorts of things: commentary, and member function declarations. Commentary is usually at the beginning of the class definition that tells what data an object of the class represents. Typically, this will be something like a date, a bank account, or a person in a company, or the state of a simulation of some kind. In addition to this, the declaration (prototype) of each public member function should have comments that tell you all you need to know about the use of that member function. It is important that the interface of the class give all the necessary information for the use of the class and its members.

The implementation of a class tells how the class interface is realized as code. The implementation includes private members, definitions of both the public member functions and any private member functions. You need the implementation to run a program that uses the ADT.

  1. What is the reason for separating the interface from the implementation of an ADT?

Answer:

One obvious benefit is that you can change your client (program that uses the ADT) without requiring that the ADT details be changed. The other benefit is that the ADT author can change the ADT implementation (but not the interface) of the ADT without requiring the client to do anything but relink his code.

 

 

Chapter 7 – Constructors and Other Tools Test Questions

 

These test questions are fill in the blank, multiple choice, and true false.  The multiple-choice questions may have more than one correct answer. There is one matching question. Mark all of the correct answers for full credit. True/false questions require an explanation in addition to the true/false response. If the response is false, a correction is required.

True False:

Comment required.

  1. A constructor is a special kind of member function. It is automatically called when an object of that class is declared.

Answer: True

Explanation: The purpose of a constructor is to automatically do any needed initialization.

  1. A constructor is always named construct with class name attached. If the class is Foo, then the constructor name is constructFoo.

Answer: False

Explanation. The name of the constructor is just the name of the class.

 

  1. A constructor is like a function. It can return any type value needed.

Answer: False.

Explanation: A constructor may not return any value, not even void. There can be no return type in front of the name.

  1. A constructor usually terminates by falling off the end of its block, but a return statement is permitted if there is no argument add following the word return..

Answer: True

Explanation: Since a constructor may need to terminate prior to falling off then end, and may need a return statement. However, a constructor cannot return any value whatsoever, so the return can not have an argument.

  1. You can write a class that is useful with all its constructors in the private section.

Answer: False

Explanation: Apart from friend of the class (something you will see later in this course) a class with all private constructors cannot create an object of the class. It seems useless to have a class for which you can have no objects..

  1. It is legal to call a constructor as a member function of an object of a class, as in

class A

{

public:

A(){}

A(int x, int y):xx(x), yy(y) {}

// other members

private:

int xx;

int yy;

};

int main()

{

A w;

w.A(2,3); // Is this legal?

}

Answer: False.

Explanation: You cannot call a constructor as if it were a member function. This writer’s compilers all give an error message that says the equivalent of this remark. The author of this code probably wanted w = A(2,3); which is legal, and does what this fragment appears to do.

  1. A constructor can be called implicitly or explicitly. (Implicitly means the compiler did it for you.)  In the interest of uniformity in answers, please use class A; for your examples.

Answer: True

Explanation: A constructor can be implicitly called with the declaration A x;. The default constructor is called explicitly with syntax is A x = A();

If the  declaration is  A x(2), the constructor is called implicilty. The equvalent explicit constructor call is A x = A(2); and so on.

  1. A class may not have another class type object as a member.

Answer: False

Explanation: A class type may be treated exactly like any other type. An int can be a member of a class, so can another class be a type of a member of another class.

  1. Any use of the keyword const is a promise to the compiler, and a request to the compiler to enforce the promise. What promises?

Answer: True.

Explanation: We have seen several uses of const. A const call-by-reference parameter promises not to write code that could change the parameter, hence not to write code that could change the argument..  A const identifier definition promises not to write code that could change the identifier. Finally, a const member function.promises not to write code in the member function that could change the state of the calling object.

  1. The keyword static is used in a static function declaration in a class but not in the function definition.

Answer: True

Explanation: The keyword static on an external definition of a static function is not allowed. The error message suggests confusion with a static global function (which we have not studied.)

  1. Vector assignment is well behaved.

Answer: True

Explanation: Vector assignment will do an element by element copy of the vector on the right into the vector on the left. It will manage space as needed, if more on the left if needed. The copy will be a real copy, not an alias. Note that assignment of vectors is as good (or bad) as the assignment of the base type.

  1. The functions or data members declared in the private: section of a class can be accessed only in the definition those functions declared in that class. Note that friend functions are also declared (but not defined) in the class to which they are friends, so they also have access to private as well as public

Answer True.

Explanation: Access to members declared in the private: section of a class, function or data, is granted to those functions declared anywhere in that class, public as well as private functions. Those denied access are functions declared anywhere else.

  1. The set of integers ranging from -MAXINT to MAXINT make up the int data type.

Answer: False.

Explanation: A data type has two parts. One, the set of values, two the set of operations.

  1. Inline functions are always more efficent than noninline functions.

Answer: False

Explanation: For larger functions inline can be less efficient.

 

  1. A static variable of a class cannot be changed.

Answer: False

Explanation: The static member can be accesses and assigned as

ClassName::staticMember = 17.0; //if the type is double

  1. size and capacity of a vector are two names for the same thing.

Answer:  false

Explanation: the size member function returns the number of elements inserted in the vector. The capacity member function returns the number of elements that a vector can hold without requiring reallocation.

 

  1. Assignment behaves essentially the same for vectors as for arrays.

Answer: false

Explanation: There is no assignment for arrays. The programmer must carry out the copy member by member.

  1. A local class and a nested class are the same thing.

Answer: False

Explanation: A local class has its definition in a block, whereas a nested class has its definition within another class.

  1. If v is a vector and i is an int variable, then in the following the value of i can be any nonnegative int value:

v[i] = i;

Answer: False

  1. If we use an out of range index with a vector, there be an error message from the compiler.

Answer: False.

Explanation: The Standard Library vector was designed for speed, not safety. There is no range checking done for indexing. As we shall see, there is a range checked member function for the string and vector.

Multiple Choice
  1. Given the class definition,

class A

{

public:

A(){}

A(int x, char y):xx(x), yy(y) {}

// other members

private:

int xx;

char yy;

};

Tell which definition below is legal.

If legal, tell whether it is a definition of an object of class A.

If the definition is a legal and defines a class A object, tell which constructor is called for each of the following definitions.

Identify the constructor like this: If the constructor for class A with two int arguments is called, respond with A(int, int).

  1. A x(2, ‘A’);
  2. A x;
  3. A x = A(2, ‘A’);
  4. A x(1);
  5. A x( );

Answer:

Part a) is legal, A(int,char) is called. Part b) is legal, the default constructor, A( ) is called. This is sometime (in truth, infrequently) written A(void). Part c) is legal, A(int, char) is called.

Explanation:

  1. d) is not legal. It tries to call A(int), but there is no such constructor defined. Part e) defines a function taking no arguments and returning a class A
  1. A class member that is to be shared among all objects of a class is called
    1. A const member
    2. A reference member
    3. A static member.
    4. A value member
    5. A function member

Answer:  c) a static member

Explanation:

Static function members do not use  need a calling object. They provide the usefulness of a global data members without the abuses that are usually associated with global members in part because the static data member is local to the class. A static member variable must be initialized outside the class (by the class author).

A static member function does not use data from any object, so in that sense it is shared by all members.

Static member functions act as global functions for the class without affecting the rest of the program. Like real global functions, they do not have access to data in the any object. The association of static member function with the class is explicit and obvious, but for real global function this is not true.

  1. In a vector, which of the following statements is true?
    1. Indexing vector access is range checked.
    2. The range of legal index values for a vector is 0 to the value of size()-1
    3. To add a value use the member function push_front( )
    4. To manage size of reserve use reserve(newReserve)
    5. To increase or decrease a vector’s size v.new_size(newSize);

Answer: b) and d) are correct

Explanation: a) indexing is not  range checked.

  1. b) index values run from 0 to one less than the number of elements
  2. c) use push_back( ) to add elements at the back. The mentioned function is not available on the vector. In e) to increase or decrease a vector, use v.resize(newSize);
  1. Which of the following are accurate comparisons between call-by-value and const call-by-reference?
    1. Both protect against changing the caller’s argument.
    2. Both are very fast for all sizes of objects.
    3. Call-by-value copies the argument whereas const call-by-reference does not
    4. Call by value uses more memory than const call-by-reference in making the copy.

Answer:  a) , c) and d) are correct

Explanation: a) call-by-value makes a copy and uses the copy. This protects against changing the caller’s argument. Const call-by-reference provides a programming language mechanism to prevent the author of the code from writing code that will change the parameter so protects the caller’s argument. b) is wrong, call-by-value is much slower because it makes a copy.

  1. Which of the following are vector member functions studied in this chapter?
    1. push_back(baseTypeObject) puts object on the back of the vector
    2. indexing, like an array, with index values 0 to size( ) -1
    3. a constructor that takes an int argument and constructs a vector of that many base type default constructed elements.
    4. size( ) tells how many base type objects have been inserted
    5. reserve(newReserve) to tell a vector to change the capacity.

Answer: All are members of the vector.

  1. Concerning nested classes, which of the following are true?
    1. You can define a class within a class.
    2. The inner class must always be public
    3. The inner class is within the scope of the outer class.
    4. Qualification by the outer class name with the scope resolution operator is necessary to use the inner class outside the outer class.
    5. A local class can contain static members.

Answer: a) c) d) are correct

Explanation: b):A the inner class may be either public or private. e) is the opposite of a correct statement. A local class cannot have static members.

  1. Which of the following is correct regarding presence and behavior of constructor is correct. Assume that the class name is C.
    1. To use the declaration, C x; requires a default constructor must be present.
    2. To invoke the default constructor, the syntax must be C x();
    3. A constructor is called automatically when you declare an object of class type, but any constructor can be called after declaration to set all the member variables to a known state.
    4. An explicit call to a constructor creates an anonymous object, which can be assigned.
    5. In spite of the fact that a constructor appears to be a member function, a constructor may not be called as if it were a member function

Answer: Correct responses are: a) c) d) e)

Explanation: b) defines a function that takes no arguments and returns class C object. Part c) is right as far as it goes. It should mention that the constructor may not be called as if it were a member function; rather, it must be called to generate an anonymous object, which is assigned to change the state of an object.

  1. Which of the following are correct?
    1. A constructor must be declared for each class.
    2. A constructor must be declared with a return type
    3. A default constructor can only be provided by the compiler.
    4. A class can have only one default constructor.
    5. A class can have only one constructor.

Answer: d) is the only one that is correct.

Explanation: a) is wrong. The compiler will provide a default constructor if the class author does not.  b) is wrong. In fact, a constructor may not have a return type. c) is wrong. In fact, as we will see later in this course, if the class author provides a constructor, the compiler will not provide a default constructor. If default constructor is needed under these circumstances, the class author must provide one.

  1. Which of the following are legal access to the class or struct members? Assume each is outside of the class member definitions,

struct S          class C          class D

{                 {                {

int x;            int x;         public:

int y;            int y;           int x;

}                 private:           int y;

S s;                int z;         private:

};                 int z;

C c;             };

D d;

  1. a) s.x
  2. b) c.x
  3. c) d.x
  4. d) c.z
  5. e) d.z

Answer:

  1. a) s.x is legal. struct members are public unless otherwise specified.
  2. b) c.x is illegal. class members are private unless otherwise declared public, unless used in a member function definition. No member function for class C are present.
  3. c) d.x is legal. x is declared to be public within class D
  4. d) c.z is illegal. All members of a class are private unless declared public, unless used in a member function definition. No member function for class C are present.
  5. e) d.z is illegal, unless this is in a definition of a member of class D. No member functions are present.
  6. A constructor
  7. can only be used to initialize
  8. must initialize all member variables
  9. can do anything any other method can do.
  10. usually initializes all, or most, member variables

Answer: c and d

Explanation: c) is right. The exception  is that a constructor cannot be called as if it were a member function. d) Aconsructor’s purpose is allcating and initializing resources.

  1. If a class represents an amount of money (in US currency like $9.99), then

the amount (like $9.99) could reasonably be stored in

  1. A member variable of type double.
  2. Two member variables of type int.
  3. A string of characters (like “9.99”).
  4. None of the above.

Answer a, b, and c.

  1. If a class represents a date (such as July 4, 1776), then the date could reasonably be stored in
  2. A member variable of type double.
  3. Two member variables of type int.
  4. Three member variables of type int.
  5. A string of characters (like “July 4, 1776”).
  6. A string for the month and two int

Answer c, d, and e

Free Form Questions:
  1. What is a default constructor? When does a class not have a default constructor?

Answer: A default constructor is a constructor that takes no arguments. If a class has any author supplied constructors with parameters, then the class will not have a default constructor unless the class author supplies a default constructor.

  1. Suppose you have a class whose objects are very, very large. Briefly, describe the advantages and drawbacks of call-by-value and call-by-reference for large objects. Describe a parameter passing mechanism that will allow the safety of call-by-value and the efficiency of call-by-reference.

Answer:

Call-by-value protects the caller’s copy of the data from change. However, significant memory space must be used for the copy in the value parameter and copying data takes time. Call-by-reference endangers the caller’s data.

The required mechanism uses a const call-by-reference parameter.

Example:

class A{/* stuff */};

void foo(const A& arg);

Explanation:

Const reference will provide protection against inadvertent change in the caller’s argument. The compiler will refuse to compile any code that makes the parameter an l-value.

  1. Why is it an error to add a const modifier, as shown to the declaration for the member function input given here?

class BankAccount

{

public:

void input( ) const;

// other members

};

Answer:

If an input routine actually contains code to do input, the function will not compile.

Explanation:

The purpose of and input function is to change the state of the calling object. The purpose of the const modifier placed as shown is to prevent compiling of code that changes the state of the calling object.

 

  1. Given the definitions below. Each occurrence of a const is a promise to the compiler that the compiler will enforce. What is the promise in each case?

const int x = 17;     //a)

class A

{

public:

A( );

A(int n):

int f( ) const;     // b)

int g(const A& x);  // c)

private:

int i;

};

Answer:

In a) the promise is that any code written by the author will not change x.

In  b) the promise is that any code written by the author in the definition of A::f( )will not change the state of the calling object.

In c) the promise is that any code written by the author in the definition of A::g(const A&x)will not change the argument in the invocation of this function.

  1. Describe the differences between a call to an inline function member and a function that is not declared inline.. What advantages are there to inline? What disadvantages?

Answer:

When a function is invoked, normally  the function’s executable code has been placed to the side. The compiler puts a function call in the caller’s executable. The parameter passing mechanisms are set up so control is sent to the function’s code. There is only

one instance of the called function’s code no matter how many objects there are and no matter how many times the member function is called.

In-line definitions do things differently. The compiler places  the body of inline functions in the execution stream at the place of the call with variable set in accord with the parameter calling mechanism.. Inlining is done only for small functions. (In fact, one of my compilers refuses to inline any function with a switch or loop.)

The advantage of inlined functions is that inline functions tend to be faster, at least for small functions. The non-inline overhead of setting up the parameter passing mechanism and transferring control is avoided. The disadvantages of inlined functions are that the code will be larger if the inline function is called many times. The code will be slower for large inline functions than for equivalent non-inlined functions.

  1. Explain why data members, in particular should be placed in the private section of a class.

Answer: A C++ class contains a complete list of all the functions that can access the private members of that class. This ensures complete control of the private data. This property is important for understanding a program in general. If the data were not private, the client programmer could corrupt the data in any way that the client sees fit. This has considerable potential for mischief.

  1. Describe in terms of who needs access to class members why the public members should come first in a class definition.

Answer: The client is more interested in the public members. The client cannot access the private members, and thus has no real (direct) use for them. Hence the public members should be placed first in a class.

  1. Given the definitions below. Rewrite the definition of this class so that functions f()const and g(const A& x) are inline.

const int x = 17;

class A

{

public:

A( );

A(int n);

int f( ) const;

int g(const A& x);

private:

int i;

};

Answer:

const int x = 17;

class A

{

public:

A( );

A(int n):

int f( ) const

{

// code implementing f()

}

int g(const A& x)

{

// code implementing g()

}

 

private:

int i;

};

 

 

0.0/5
0 reviews
0
0
0
0
0

There are no reviews yet.

Be the first to review “Absolute C++ 5th Edition by Walter Savitch – Test Bank”