New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
introduction java program
C++ Primer Plus 6th Edition Stephen Prata - Solutions
Suppose you define a function that takes a reference to a base-class object as an argument. Why can this function also use a derived-class object as an argument?
Suppose you define a function that takes a base-class object as an argument (that is, the function passes a base-class object by value).Why can this function also use a derived-class object as an argument?
Why is it usually better to pass objects by reference than by value?
Suppose Corporation is a base class and PublicCorporation is a derived class. Also suppose that each class defines a head() member function, that ph is a pointer to the Corporation type, and that ph is assigned the address of a PublicCorporation object. How is ph->head() interpreted if the base
What’s wrong, if anything, with the following code?class Kitchen{private:double kit_sq_ft;public:Kitchen() {kit_sq_ft = 0.0; }virtual double area() const { return kit_sq_ft * kit_sq_ft; }};class House : public Kitchen{private:double all_sq_ft;public:House() {all_sq_ft += kit_sq_ft;}double
For each of the following sets of classes, indicate whether public or private derivation is more appropriate for Column B: A class Bear class Kitchen class Person class Person. class Person, class Automobile B class PolarBear class Home class Programmer class HorseAndJockey class Driver
The Wine class has a string class object member (see Chapter 4) that holds the name of a wine and a Pair object (as discussed in this chapter) of valarray objects (as discussed in this chapter).The first member of each Pair object holds the vintage years, and the second member holds the numbers of
Suppose you have the following definitions:class Frabjous {private:char fab[20];public:Frabjous(const char * s = "C++") : fab(s) { }virtual void tell() { cout << fab; }};class Gloam {private:int glip;Frabjous fb;public:Gloam(int g = 0, const char * s = "C++");Gloam(int g, const Frabjous &
This exercise is the same as Programming Exercise 1, except that you should use private inheritance instead of containment.Again, a few typedefs might prove handy.Also you might contemplate the meaning of statements such as the following:PairArray::operator=(PairArray(ArrayInt(),ArrayInt()));cout
Suppose you have the following definitions:class Frabjous {private:char fab[20];public:Frabjous(const char * s = "C++") : fab(s) { }virtual void tell() { cout << fab; }};class Gloam : private Frabjous{private:int glip;public:Gloam(int g = 0, const char * s = "C++");Gloam(int g, const Frabjous
Define a QueueTp template.Test it by creating a queue of pointers-to-Worker (as defined in Listing 14.10) and using the queue in a program similar to that in Listing 14.12.Here is a sample run of the program in Listings 14.10, 14.11, and 14.12:Enter the employee category:w: waiter s: singer t:
Suppose you have the following definition, based on the Stack template of Listing 14.13 and the Worker class of Listing 14.10:Stack sw;Write out the class declaration that will be generated. Just do the class declaration, not the non-inline class methods. Listing 14.10 workermi.h // workerni.h --
A Person class holds the first name and the last name of a person. In addition to its constructors, it has a Show() method that displays both names.A Gunslinger class derives virtually from the Person class. It has a Draw() member that returns a type double value representing a gunslinger’s draw
Use the template definitions in this chapter to define the following:An array of string objectsA stack of arrays of doubleAn array of stacks of pointers to Worker objectsHow many template class definitions are produced in Listing 14.18?The output of the program in Listing 14.18 has one line for
Here are some class declarations:// emp.h -- header file for abstr_emp class and children#include#includeclass abstr_emp{private:std::string fname; // abstr_emp's first namestd::string lname; // abstr_emp's last namestd::string job;public:abstr_emp();abstr_emp(const std::string & fn, const
Describe the differences between virtual and nonvirtual base classes.
What’s wrong with the following attempts at establishing friends?a. class snap {friend clasp;...};class clasp { ... };b. class cuff {public:void snip(muff &) { ... }...};class muff {friend void cuff::snip(muff &);...};c. class muff {friend void cuff::snip(muff &);...};class cuff
Modify the Tv and Remote classes as follows:a. Make them mutual friends.b. Add a state variable member to the Remote class that describes whether the remote control is in normal or interactive mode.c. Add a Remote method that displays the mode.d. Provide the Tv class with a method for toggling the
You’ve seen how to create mutual class friends. Can you create a more restricted form of friendship in which only some members of Class B are friends to Class A and some members of A are friends to B? Explain.
Modify Listing 15.11 so that the two exception types are classes derived from the logic_error class provided by the header file. Have each what() method report the function name and the nature of the problem. The exception objects need not hold the bad values; they should just support the what()
This exercise is the same as Programming Exercise 2, except that the exceptions should be derived from a base class (itself derived from logic_error) that stores the two argument values, the exceptions should have a method that reports these values as well as the function name, and a single catch
What problems might the following nested class declaration have?class Ribs{private:class Sauce{int soy;int sugar;public:Sauce(int s1, int s2) : soy(s1), sugar(s2) { }};...};
How does throw differ from return?
Listing 15.16 uses two catch blocks after each try block so that the nbad_index exception leads to the label_val() method being invoked. Modify the program so that it uses a single catch block after each try block and uses RTTI to handle invoking label_val() only when appropriate.Here is the output
Suppose you have a hierarchy of exception classes that are derived from a base exception class. In what order should you place catch blocks?
Consider the Grand, Superb, and Magnificent classes defined in this chapter. Suppose pg is a type Grand * pointer that is assigned the address of an object of one of these three classes and that ps is a type Superb * pointer.What is the difference in how the following two code samples behave?if (ps
How is the static_cast operator different from the dynamic_cast operator?
A palindrome is a string that is the same backward as it is forward. For example,“tot” and “otto” are rather short palindromes. Write a program that lets a user enter a string and that passes to a bool function a reference to the string.The function should return true if the string is a
Consider the following class declaration:class RQ1{private:char * st; // points to C-style stringpublic:RQ1() { st = new char [1]; strcpy(st,""); }RQ1(const char * s){st = new char [strlen(s) + 1]; strcpy(st, s); }RQ1(const RQ1 & rq){st = new char [strlen(rq.st) + 1]; strcpy(st, rq.st); }~RQ1()
Do the same problem as given in Programming Exercise 1 but do worry about complications such as capitalization, spaces, and punctuation.That is,“Madam, I’m Adam” should test as a palindrome. For example, the testing function could reduce the string to “madamimadam” and then test whether
Redo Listing 16.3 so that it gets it words from a file. One approach is to use a vector object instead of an array of string.Then you can use push_back() to copy how ever many words are in your data file into the vector object and use the size() member to determine the length of the word list.
Name at least two advantages string objects have over C-style strings in terms of ease-of-use.
Write a function that takes a reference to a string object as an argument and that converts the string object to all uppercase.
Write a function with an old-style interface that has this prototype: int reduce(long ar[], int n);The actual arguments should be the name of an array and the number of elements in the array.The function should sort an array, remove duplicate values, and return a value equal to the number of
Which of the following are not examples of correct usage (conceptually or syntactically) of auto_ptr? (Assume that the needed header files have been included.)auto_ptr pia(new int[20]);auto_ptr (new string);int rigue = 7;auto_ptrpr(&rigue);auto_ptr dbl (new double);
Do the same problem as described in Programming Exercise 4, except make it a template function:templateint reduce(T ar[], int n);Test the function in a short program, using both a long instantiation and a string instantiation.
Redo the example shown in Listing 12.12, using the STL queue template class instead of the Queue class described in Chapter 12. Listing 12.12 bank.cpp // bank.cpp -- using the Queue interface // compile with queue.cpp #include #include // for rand() and srand() #include // for time() #include
If you could make the mechanical equivalent of a stack that held golf clubs instead of numbers, why would it (conceptually) be a bad golf bag?
Why would a set container be a poor choice for storing a hole-by-hole record of your golf scores?
A common game is the lottery card.The card has numbered spots of which a certain number are selected at random.Write a Lotto() function that takes two arguments. The first should be the number of spots on a lottery card, and the second should be the number of spots selected at random.The function
Because a pointer is an iterator, why didn’t the STL designers simply use pointers instead of iterators?
Compared to an array, a linked list features easier addition and removal of elements but is slower to sort.This raises a possibility: Perhaps it might be faster to copy a list to an array, sort the array, and copy the sorted result back to the list than to simply use the list algorithm for sorting.
Mat and Pat want to invite their friends to a party.They ask you to write a program that does the following:Allows Mat to enter a list of his friends’ names.The names are stored in a container and then displayed in sorted order.Allows Pat to enter a list of her friends’ names.The names are
Why didn’t the STL designers simply define a base iterator class, use inheritance to derive classes for the other iterator types, and express the algorithms in terms of those iterator classes?
If Listing 16.9 were implemented with list instead of vector, what parts of the program would become invalid? Could the invalid part be fixed easily? If so, how? Table 16.9 Some list Member Functions Function void merge (list& x) void remove (const T & val) void sort () void splice (iterator
Give at least three examples of convenience advantages that a vector object has over an ordinary array.
Modify Listing 16.9 (vect3.cpp) as follows:Here’s a sample run of the program in Listing 16.9:Enter book title (quit to quit): The Cat Who Can Teach You Weight LossEnter book rating: 8Enter book title (quit to quit): The Dogs of DharmaEnter book rating: 6Enter book title (quit to quit): The Wimps
Consider the TooBig functor in Listing 16.15.What does the following code do, and what values get assigned to bo? bool bo = TooBig(10)(15);One functor (f100) is a declared object, and the second (TooBig(200)) is ananonymous object created by a constructor call. Here’s the output of the
What role does the iostream file play in C++ I/O?
Write a program that counts the number of characters up to the first $ in input and that leaves the $ in the input stream.
Why does typing a number such as 121 as input require a program to make a conversion?
Write a program that copies your keyboard input (up to the simulated end-of-file) to a file named on the command line.
What’s the difference between the standard output and the standard error?
Write a program that copies one file to another. Have the program take the filenames from the command line. Have the program report if it cannot open a file.
Why is cout able to display various C++ types without being provided explicit instructions for each type?
Write a program that opens two text files for input and one for output. The program should concatenate the corresponding lines of the input files, use a space as a separator, and write the results to the output file. If one file is shorter than the other, the remaining lines in the longer file
What feature of the output method definitions allows you to concatenate output?
Mat and Pat want to invite their friends to a party, much as they did in Programming Exercise 8 in Chapter 16, except now they want a program that uses files. They have asked you to write a program that does the following:Reads a list of Mat’s friends’ names from a text file called mat.dat,
Write a program that requests an integer and then displays it in decimal, octal, and hexadecimal forms. Display each form on the same line, in fields that are 15 characters wide, and use the C++ number base prefixes.
Consider the class definitions of Programming Exercise 5 in Chapter 14,“Reusing Code in C++”. If you haven’t yet done that exercise, do so now.Then do the following:Write a program that uses standard C++ I/O and file I/O in conjunction with data of types employee, manager, fink, and highfink,
Write a program that requests the following information and that formats it as shown:Enter your name: Billy GruffEnter your hourly wages: 12Enter number of hours worked: 7.5First format:Billy Gruff: $ 12.00: 7.5Second format:Billy Gruff : $12.00 :7.5
Here is part of a program that reads keyboard input into a vector of string objects, stores the string contents (not the objects) in a file, and then copies the file contents back into a vector of string objects:int main(){using namespace std;vector vostr;string temp;// acquire stringscout <<
Consider the following program://rq17-8.cpp#includeint main(){using namespace std;char ch;int ct1 = 0;cin >> ch;while (ch != 'q'){ct1++;cin >> ch;}int ct2 = 0;cin.get(ch);while (ch != 'q'){ct2++;cin.get(ch);}cout << "ct1 = " << ct1 << "; ct2 = " << ct2 <<
Both of the following statements read and discard characters up to and including the end of a line. In what way does the behavior of one differ from that of the other?while (cin.get() != '\n')continue;cin.ignore(80, '\n');
In Listing 6.10, what advantage would there be in using character labels, such as a and c, instead of numbers for the menu choices and switch cases?Here is a sample run of the executive menu program in Listing 6.10:Please enter 1, 2, 3, 4, or 5:1) alarm 2) report3) alibi 4) comfort5) quit4Your
What are the three steps in using a function?
Write a program that repeatedly asks the user to enter pairs of numbers until at least one of the pair is 0. For each pair, the program should use a function to calculate the harmonic mean of the numbers. The function should return the answer to main(), which should report the result. The harmonic
Construct function prototypes that match the following descriptions:a. igor() takes no arguments and has no return value.b. tofu() takes an int argument and returns a float.c. mpg() takes two type double arguments and returns a double.d. summation() takes the name of a long array and an array size
Write a program that asks the user to enter up to 10 golf scores, which are to be stored in an array. You should provide a means for the user to terminate input prior to entering 10 scores. The program should display all the scores on one line and eport the average score. Handle input, display, and
Here is a structure declaration:struct box{char maker[40];float height;float width;float length;float volume;};a. Write a function that passes a box structure by value and that displays the value of each member.b. Write a function that passes the address of a box structure and that sets the volume
Many state lotteries use a variation of the simple lottery portrayed by Listing 7.4. In these variations you choose several numbers from one set and call them the field numbers. For example, you might select five numbers from the field of 1–47).You also pick a single number (called a mega number
Write a function that takes three arguments: a pointer to the first element of a range in an array, a pointer to the element following the end of a range in an array, and an int value. Have the function set each element of the array to the int value.
Write a function that takes a double array name and an array size as arguments and returns the largest value in that array. Note that this function shouldn’t alter the contents of the array.
Define a recursive function that takes an integer argument and returns the factorial of that argument. Recall that 3 factorial, written 3!, equals 3 × 2!, and so on, with 0! defined as 1. In general, if n is greater than zero, n! = n * (n - 1)!.Test your function in a program that uses a loop to
Why don’t you use the const qualifier for function arguments that are one of the fundamental types?
Write a program that uses the following functions:Fill_array() takes as arguments the name of an array of double values and an array size. It prompts the user to enter double values to be entered in the array. It ceases taking input when the array is full or when the user enters non-numeric input,
Redo Listing 7.7, modifying the three array-handling functions to each use two pointer parameters to represent a range. The fill_array() function, instead of returning the actual number of items read, should return a pointer to the location after the last location filled; the other functions can
What are the three forms a C-style string can take in a C++ program?
Redo Listing 7.15 without using the array class. Do two versions:a. Use an ordinary array of const char * for the strings representing the season names, and use an ordinary array of double for the expenses.b. Use an ordinary array of const char * for the strings representing the season names, and
Write a function that has this prototype:int replace(char * str, char c1, char c2);Have the function replace every occurrence of c1 in the string str with c2, and have the function return the number of replacements it makes.
What does the expression *"pizza" mean? What about "taco"[2]?
This exercise provides practice in writing functions dealing with arrays and structures. The following is a program skeleton. Complete it by providing the described functions:#includeusing namespace std;const int SLEN = 30;struct student {char fullname[SLEN];char hobby[SLEN];int ooplevel;};//
C++ enables you to pass a structure by value, and it lets you pass the address of a structure. If glitz is a structure variable, how would you pass it by value? How would you pass its address? What are the trade-offs of the two approaches?
Design a function calculate() that takes two type double values and a pointer to a function that takes two double arguments and returns a double. The calculate() function should also be type double, and it should return the value that the pointed-to function calculates, using the double arguments
The function judge() has a type int return value. As an argument, it takes the address of a function. The function whose address is passed, in turn, takes a pointer to a const char as an argument and returns an int. Write the function prototype.
Suppose we have the following structure declaration:struct applicant {char name[30];int credit_ratings[3];};a. Write a function that takes an applicant structure as an argument and displays its contents.b. Write a function that takes the address of an applicant structure as an argument and displays
Suppose the functions f1() and f2() have the following prototypes:void f1(applicant * a);const char * f2(const applicant * a1, const applicant * a2);Declare p1 as a pointer that points to f1 and p2 as a pointer to f2. Declare ap as an array of five pointers of the same type as p1, and declare pa as
What kinds of functions are good candidates for inline status?
Write a function that normally takes one argument, the address of a string, and prints that string once. However, if a second, type int, argument is provided and is nonzero, the function should print the string a number of times equal to the number of times that function has been called at that
Suppose the song() function has this prototype:void song(const char * name, int times);a. How would you modify the prototype so that the default value for times is 1?b. What changes would you make in the function definition?c. Can you provide a default value of "O, My Papa" for name?
Write a function that takes a reference to a string object as its parameter and that converts the contents of the string to uppercase. Use the toupper() function described in Table 6.4 of Chapter 6.Write a program that uses a loop which allows you to test the function with different input.A sample
The CandyBar structure contains three members. The first member holds the brand name of a candy bar. The second member holds the weight (which may have a fractional part) of the candy bar, and the third member holds the number of calories (an integer value) in the candy bar. Write a program that
Write overloaded versions of iquote(), a function that displays its argument enclosed in double quotation marks. Write three versions: one for an int argument, one for a double argument, and one for a string argument.
The following is a structure template:struct box{char maker[40];float height;float width;float length;float volume;};a. Write a function that has a reference to a box structure as its formal argument and displays the value of each member.b. Write a function that has a reference to a box structure
What changes would need be made to Listing 7.15 so that the functions fill() and show() use reference parameters?Here’s a sample run:Enter Spring expenses: 212Enter Summer expenses: 256Enter Fall expenses: 208Enter Winter expenses: 244EXPENSESSpring: $212Summer: $256Fall: $208Winter: $244Total:
The following is a program skeleton:#includeusing namespace std;#include // for strlen(), strcpy()struct stringy {char * str; // points to a stringint ct; // length of string (not counting '\0')};// prototypes for set(), show(), and show() go hereint main(){stringy beany;char testing[] = "Reality
Write a template function max5() that takes as its argument an array of five items of type T and returns the largest item in the array. (Because the size is fixed, it can be hard-coded into the loop instead of being passed as an argument.) Test it in a program that uses the function with an array
The following are some desired effects. Indicate whether each can be accomplished with default arguments, function overloading, both, or neither. Provide appropriate prototypes.a. mass(density, volume) returns the mass of an object having a density of density and a volume of volume, whereas
Write a template function maxn() that takes as its arguments an array of items of type T and an integer representing the number of elements in the array and that returns the largest item in the array. Test it in a program that uses the function template with an array of six int value and an array
Write a function template that returns the larger of its two arguments.
Showing 500 - 600
of 741
1
2
3
4
5
6
7
8
Step by Step Answers