Sample Chapter

INSTANT DOWNLOAD

 

Test Bank Of Absolute Java 5th Edition By Walter, Savitch

 

Chapter 1 – 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, and, if false, also require a correction.

True False:

Comment required.

  1. OOP is an acronym that means Object Oriented Programming.

Answer: True.

Explanation: OOP is currently popular and is a powerful programming technique for a large class of problems.

  1. C++ not only supports OOP but also supports other programming styles.

Answer: True.

Explanation: C++ supports OOP and traditional procedure oriented programming.

  1. The namespace facility is a tool used that assists in the study of genealogy.

Answer: False.

Explanation: The namespace facility helps prevent the libraries from “preempting all the good names,” and allows us to use names we want whether the library has used them.

  1. In C++ the variables Alpha, ALPHA and AlphA are the same identifier.

Answer: False.

Explanation: C++ is case sensitive, these are different identifiers.

  1. In C++ the compiler will infer the type intended for a variable from the context in which the variable occurs.

Answer: False.

Explanation: C++ requires every identifier to be declared prior to use. The type is specified in the declaration.

  1. A C++ declaration introduces only an identifier’s spelling and specifies its type.

Answer: True.

Explanation: A declaration introduces the spelling and type, whereas a definition is a declaration that also allocates memory.

  1. A C++ declaration is a definition that also allocates storage for an identifier’s value (or function’s body etc.).

Answer: True.

Explanation: A declaration introduces the spelling and type, whereas a definition is a declaration that also allocates memory.

  1. The range of values for an int variable is from about 0 to +2

Answer: False:

Explanation: The correct range is about –2 Billion to +2 Billion.

  1. The names x, y, and z are satisfactory variable names for the lengths of the legs and hypotenuse of a triangle.

Answer: False.

Explanation: Names should communicate to the human reader the meaning of the value. These identifiers do not communicate the meaning of their values..

  1. In C++ you can assign an expression of type int to a variable of type double with no problem.

Answer: True.

Explanation: Assignment from an integer type to a floating point type can lose information and should be avoided. Some compilers will warn, others may give an error message, but you should avoid this.

  1. In C++ you can assign an expression of type double to a variable of type int with no problem.

Answer: False.

Explanation: In general assigning a floating point value to an integer variable mostly loses information. A warning message (or an error message) is issued by C++ compilers.

  1. To put a character into a cstring constant that causes the output to continue on the next line, insert the escape sequence t into the string constant.

Answer: False.

Explanation: t is the tab escape sequence. Use n instead.

  1. If we execute this code in an otherwise correct and complete program:

n = 1;

n = (n++) + (n++);

the value of n is guaranteed to be 3 after the second line executes.

Answer: False.

Explanation: Some compilers may give the value 3. The result of such code is dependent on the compiler implementation. The C++ Standard says such code is illegal, and the Standard says the results are undefined, meaning the compiler can do anything with it that suits the compiler writer. One of my compilers gives the value 4 to n.

  1. If we execute the code fragment in an otherwise complete, correct program:

n = 1;

cout << n++ << ” ” << n++ << ” ” << n++ << endl;

the output is guaranteed to be 1 2 3.

Answer: False.

Explanation: The code is illegal because its execution depends on the order of evaluation of arguments.  Various compilers give different answers. One compiler this writer uses gives 3 2 1.

  1. C++ uses only /* */ for comments.

Answer: False.

Explanation: C++ uses /* */ comments and  // “here to the end of the line” comments.

  1. A program’s comments should connect the program code to the problem being solved.

Answer: True.

Explanation: The purpose of comments in a program is to help the human reader of the code to connect the program to the problem being solved. Comments are so important there is an aphorism, often quoted by expert programmers: “If the comments and the code disagree, then both are probably wrong.

  1. A program should have a comment on every line.

Answer: False.

Explanation: This would be satisfactory only on a very complicated assembly language program for an inexperienced programmer.

  1. Comments have no value whatsoever and do not belong in a program.

Answer: False.

Explanation: The purpose of comments in a program is to help the human reader of the code to connect the program to the problem being solved. Comments are valuable.

  1. The most difficult programming language construct to learn to use properly is the comment.

Answer: True.

Explanation: How many comments and what should be in the comment is very hard to decide because these depend on who is the intended reader of the code (and comments).

  1. A computer program is a set of instructions intended for only the computer to follow.

Answer: False.

Explanation: A computer program is also intended for human beings to read, and the comments are intended to make this job easier.

Fill in the blank
  1. In C++, a legal identifiers may contain these kinds of characters _______________, ______________, ______________

Answer: Letters, digits, underscore

Explanation: Some implementations allow a very few other characters such as $.

  1. The C++ very nearly contains the ______ programming language as proper subset.

Answer: (the) C (programming language)

  1. In C++, a variable that has been defined but not initialized may not be use as an ______. (l-value or r-value).

Answer: r-value

Explanation: The value of an uninitialized variable may not be fetched. C++ does not enforce this. If an uninitialized variable’s value is fetched you get whatever value was left in the memory location by a previous user. Note that the value is garbage in the dictionary sense, It is not a random value.

  1. Identifiers should at least give a hint to the human reader of the ________________ of the identifier in the context of the problem being solved.

Answer: Meaning

Explanation: Any identifier in a program that represents a quantity in a problem should be named in the program with the real life name for that quantity, or at least the should hint at the real life thing it represents.

 Multiple Choice
  1. The person responsible for the initial development of C++ was
    1. Dennis Ritchie
    2. James Gosling
    3. Brian Kernighan
    4. Bjarne Strousrup
    5. Bill Joy

Answer: d) Bjarne Stroustrup, at AT&T Bell Labs in the 1980s

  1. In C++, some of the following are legal identifiers. Which? Why?
    1. 9xyz
    2. Xyz
    3. X+yz
    4. xy_z
    5. xyz!

Anwer:

  1. 9xyz no – An identifier cannot start with a digit
  2. Xyz An identifier may have upper and lower case letters
  3. X+yz no – This has an illegal ‘+’.
  4. xy_z
  5. xyz! no – This has an illegal ‘!’.
  1. Which of the following are likely to be poor choices for an identifier in a program? Why?
    • x
  1. RATE
  • data
  1. _abc
  • A

Answer:

  1. x is too short to adequately describe a real world value.
  2. RATE suggests a rate of speed, or interest perhaps.
  3. data is perhaps a bit generic, nevertheless this writer would allow it.
  4. _abc is not a word. It does not bring anything to this writer’s mind.
  5. A is too short to adequately describe anything in the real world.

Explanation: The answers to this question are subjective.

  1. Pick the C++ keywords out of the following list.
    1. while
    2. total_weight
    3. double
    4. if
    5. number_of_bars

Answer: Keywords are a) while, c) double and d) if.

  1. Which of the following does the C++ language not support?
    1. classes
    2. global functions
    3. automatic garbage collection
    4. support for object oriented programming
    5. traditional programming techniques

Answers: C++ does not provide automatic garbage collection.

Explanation: There are free and commercial garbage collection libraries for C++. “In C++, you do not pay for what you do not use.”

  1. Before a variable in C++ is used, it must be
    1. defined
    2. initialized
    3. used in some expression
    4. begin with a capital letter
    5. contain only letters, digits and underscores.

Answer: a) defined.

  1. Which of the following types are not built into the C++ language:
    1. bool
    2. real
    3. short
    4. int
    5. long
    6. double

Answer: Item b) real is incorrect. There is no “real” type in C++. C++ does provide items a)-and c) through f) and more.

  1. A l-value is
    1. an expression that can be only be placed on the left of any operator such as +, * , /, etc.
    2. assigned a value
    3. can never have a value fetched from it
    4. is designed for use by a left-handed person

Answer: b) an l-value.
Typo should be

Answer b) assigned a value

Explanation: An l-value may be assigned a value.

  1. An r-value is
    1. an expression that can be only placed on the right of any operator such as +, *, / etc.
    2. can never be assigned a value
    3. can have a value fetched from it
    4. is designed for use by a right-handed person.

Answer: c) an r-value

Explanation: An r-value can have a value fetched from it.

  1. In C++, a variable that has been defined but not initialized may
    1. be used in any way any identifier can be used.
    2. not be used at all
    3. not be used as an l-value
    4. not be used as an r-value
    5. have its value fetched prior to assignment.

Answer: c) is correct.

Explanation: The value of an uninitialized variable may not be fetched, but a value may be assigned to an uninitialized variable.

  1. Which of the following are legal definitions with initializations? (Consider each line to be in a different scope so there is no multiple definition of identifiers.)
    1. int count = 0, limit = 19;
    2. int count(0), limit(19);
    3. int count = 0, limit(19);
    4. int limit = 19;
    5. int namespace(0);

Answer: All are legal except part e) int namespace(0); because namespace is a keyword.  Keywords are reserved so may not be used as an identifier.

Explanation: Note parts a), b), and c). Some authors advocate declaring each identifier in separate definitions on separate lines, though this takes up more lines. Advocates justify this by asserting increased readability. The instructor must decide this issue.

  1. Which of the following names might give the human reader some hint about the data that is stored in them?
    1. aa, bb, cc
    2. speed, distance, time
    3. hypotenuse, leg1, leg2
    4. v1, v2, v3
    5. principal, interest, payment

Answer: Parts b), c), and e) are OK.  Parts a) and d) are poor names.

  1. The value of the expression 0 * (9/5) + 32.0 is
    1. 0
    2. 0
    3. incorrect expression so there is no value
    4. 0
    5. incorrect expression , the / should be %

Answer: Part b)  is correct
Explanation: 9/5 evaluates to 1 using truncating int division.

  1. The value of the expression 0 * (9.0/5) + 32.0 is
    1. 0
    2. 0
    3. expression has a syntax error so there is no value
    4. 0
    5. an incorrect expression, the / should be %

Answer: Part a).

Explanation: The expression 9.0 /5 evaluates to 1.8 and the computation proceeds correctly.

  1. The following contain several #include directives that may have problems. Which have one or more problems, and what problems?
    1. #include <iostream>
    2. #include <  iostream>
    3. #include “MyStream.h”
    4. #include “cctype  “
    5. #include “This file does not exist on the system”

Answer: All Except a) and c)

Explanation: b) The space between < and iostream makes preprocessor think the file name has a space at the front of the name. In part c), the system looks in the default directory then in the system directories as it does for <files>. d) has space at the end of the file name.  e) The file name is unlikely. At the least, the situation should be examined.

Free Form Questions:
  1. In the history of the C++ language, what was the immediate predecessor of the C++ language? How is this older language related to C++?

Answer: The immediate predecessor of C++ is the C programming language. C is very nearly a proper subset of C++.

  1. Write a C++ program that outputs “My first C++ program” and then outputs a carriage return.

Answer:

#include <iostream>

using namespace std;

int main()

{

cout << “My first C++ program” << endl;

}

 

Explanation: An alternative is to place using namespace std; after the #include directive, or to place this inside the block of the function main. This depends on the local rules for placing namespace directives and definitions.

  1. Given the C++ output statements. What is the output of these lines of code? Explain.

cout << “If you have “;

cout << “a number of pods “;

cout << “you can quit.”;

cout << “n”;

Answer: If you have a number of pods you can quit.

Explanation: Note that there is a <cr> emitted by the code, which puts the next output position on the next line at the left end.

  1. What does the line

#include <iostream>

do for your program?

Answer: The #include directive provides declarations and definitions of the iostream components so that your program can use them in a way that allows the system linker to connect your program to the corresponding library.

  1. What is the difference between a warning from the compiler and an error message from the compiler?

Answer: An error message usually causes code generation to stop. A warning does not. Unless you understand what the warning is all about you should not ignore warnings.

  1. Give the declaration for two variables, feet and inches. Declare each to be of type int, and both initialized to zero in the declaration. Give both initialization alternatives.

Answer:

int feet = 0;

int inches = 0;

//Alternate initialization.

int feet (0);

int inches(0);

  1. Write a short program that contains statements to output the values of a variable that you define but neither initialize nor assign. Discuss the output you get.

Answer:

#include <iostream>

using namespace std;

int main()

{

int uninitialized;

cout << uninitialized << endl;

return 0;

}

  1. When you use a double, what is doubled? When you use a long int, how much longer is the long int than an int? Comment.

Answer: In a double, the precision part of the value is about twice the precision of a float. The size of the exponent is also increased. In most implementations, long is the same size as int.

  1. What is the value assigned to the variable in each of these cases? Explain curious results. Be careful!

int x, y;

  1. x = 1/2;
  2. y = 3.0/2.0;

double z, w, t;

  1. z = 1/2;
  2. w = 3/2;
  3. t = 3.0/2.0;

Answer:

  1. 0 is assigned.1/2 is computed using truncating integer divide which gives 0.
  2. 5 is calculated and assigned. The fractional part is discarded; 1 is stored.
  3. 0 is calculated because 1/2 is done with truncating integer divide, gives 0. The floating point value 0.0 is stored.
  4. 1 is calculated, because truncating int divide, 1.0 is stored
  5. 5 is calculated and stored.

 

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;

};