Appendix D. Answers

Day 1

Quiz

1. Interpreters read through source code and translate a program, turning the programmer’s “code,” or program instructions, directly into actions. Compilers translate source code into an executable program that can be run at a later time.

2. Every compiler is different. Be certain to check the documentation that came with your compiler.

3. The linker’s job is to tie together your compiled code with the libraries supplied by your compiler vendor and other sources. The linker lets you build your program in “pieces” and then link together the pieces into one big program.

4. Edit source code, compile, link, test (run), repeat if necessary.

Exercises

1. This program initializes two integer variables (numbers) and then prints out their sum, 12, and their product, 35.

2. See your compiler manual.

3. You must put a # symbol before the word include on the first line.

4. This program prints the words Hello World to the console, followed by a new line (carriage return).

Day 2

Quiz

1. Each time you run your compiler, the preprocessor runs first. It reads through your source code and includes the files you’ve asked for, and performs other housekeeping chores. The compiler is then run to convert your preprocessed source code to object code.

2. main() is special because it is called automatically each time your program is executed. It might not be called by any other function and it must exist in every program.

3. C++-style, single-line comments are started with two slashes (//) and they comment out any text until the end of the line. Multiline, or C-style, comments are identified with marker pairs (/* */), and everything between the matching pairs is commented out. You must be careful to ensure you have matched pairs.

4. C++-style, single-line comments can be nested within multiline, C-style comments:


         /* This marker starts a comment. Everything including
         // this single line comment,
         is ignored as a comment until the end marker */

You can, in fact, nest slash-star style comments within double-slash, C++-style comments as long as you remember that the C++-style comments end at the end of the line.

5. Multiline, C-style comments can be longer than one line. If you want to extend C++-style, single-line comments to a second line, you must put another set of double slashes (//).

Exercises

1. The following is one possible answer:


1: #include <iostream>
2: using namespace std;
3: int main()
4: {
5:    cout << "I love C++ ";
6:    return 0;
7: }

2. The following program contains a main() function that does nothing. This is, however, a complete program that can be compiled, linked, and run. When run, it appears that nothing happens because the program does nothing!


int main(){}

3. Line 4 is missing an opening quote for the string.

4. The following is the corrected program:


1: #include <iostream>
2: main()
3: {
4:        std::cout << "Is there a bug here?";
5: }

This listing prints the following to the screen:

Is there a bug here?

5. The following is one possible solution:

Image

Day 3

Quiz

1. Integer variables are whole numbers; floating-point variables are “reals” and have a “floating” decimal point. Floating-point numbers can be represented using a mantissa and exponent.

2. The keyword unsigned means that the integer will hold only positive numbers. On most computers with 32-bit processors, short integers are two bytes and long integers are four. The only guarantee, however, is that a long integer is at least as big or bigger than a regular integer, which is at least as big as a short integer. Generally, a long integer is twice as large as a short integer.

3. A symbolic constant explains itself; the name of the constant tells what it is for. Also, symbolic constants can be redefined at one location in the source code, rather than the programmer having to edit the code everywhere the literal is used.

4. const variables are “typed,” and, thus, the compiler can check for errors in how they are used. Also, they survive the preprocessor, and, thus, the name is available in the debugger. Most importantly, using #define to declare constants is no longer supported by the C++ standard.

5. A good variable name tells you what the variable is for; a bad variable name has no information. myAge and PeopleOnTheBus are good variable names, but x, xjk, and prndl are probably less useful.

6. BLUE = 102

7.    a. Good

b. Not legal

c. Legal, but a bad choice

d. Good

e. Legal, but a bad choice

Exercises

1. The following are appropriate answers for each:

a. unsigned short int

b. unsigned long int or unsigned float

c. unsigned double

d. unsigned short int

2. The following are possible answers:

a. myAge

b. backYardArea

c. StarsInGalaxy

d. averageRainFall

3. The following is a declaration for pi:


const float PI = 3.14159;

4. The following declares and initializes the variable:


float myPi = PI;

Day 4

Quiz

1. An expression is any statement that returns a value.

2. Yes, x = 5 + 7 is an expression with a value of 12.

3. The value of 201 / 4 is 50.

4. The value of 201 % 4 is 1.

5. Their values are myAge: 41, a: 39, b: 41.

6. The value of 8+2*3 is 14.

7. if(x = 3) assigns 3 to x and returns the value 3, which is interpreted as true.

if(x == 3) tests whether x is equal to 3; it returns true if the value of x is equal to 3 and false if it is not.

8. The answers are

a. False

b. True

c. True

d. False

e. True

Exercises

1. The following is one possible answer:


if (x > y)
    x = y;
else          // y > x || y == x
    y = x;

2. See exercise 3.

3. Entering 20, 10, 50 gives back a: 20, b: 30, c: 10

Line 14 is assigning, not testing for equality.

4. See Exercise 5.

5. Because line 6 is assigning the value of a-b to c, the value of the assignment is a (2) minus b (2), or 0. Because 0 is evaluated as false, the if fails and nothing is printed.

Day 5

Quiz

1. The function prototype declares the function; the definition defines it. The prototype ends with a semicolon; the definition need not. The declaration can include the keyword inline and default values for the parameters; the definition cannot. The declaration need not include names for the parameters; the definition must.

2. No. All parameters are identified by position, not name.

3. Declare the function to return void.

4. Any function that does not explicitly declare a return type returns int. You should always declare the return type as a matter of good programming practice.

5. A local variable is a variable passed into or declared within a block, typically a function. It is visible only within the block.

6. Scope refers to the visibility and lifetime of local and global variables. Scope is usually established by a set of braces.

7. Recursion generally refers to the ability of a function to call itself.

8. Global variables are typically used when many functions need access to the same data. Global variables are very rare in C++; after you know how to create static class variables, you will almost never create global variables.

9. Function overloading is the ability to write more than one function with the same name, distinguished by the number or type of the parameters.

Exercises

1. unsigned long int Perimeter(unsigned short int, unsigned short int);

2. The following is one possible answer:


unsigned long int Perimeter(unsigned short int length, unsigned short int width)
      {
        return (2*length) + (2*width);
      }

3. The function tries to return a value even though it is declared to return void and, thus, cannot return a value.

4. The function would be fine, but there is a semicolon at the end of the myFunc() function’s definition header.

5. The following is one possible answer:

Image

6. The following is one possible solution:

Image

7. The following is one possible solution:

Image

Day 6

Quiz

1. The dot operator is the period (.). It is used to access the members of a class or structure.

2. Definitions of variables set aside memory. Declarations of classes don’t set aside memory.

3. The declaration of a class is its interface; it tells clients of the class how to interact with the class. The implementation of the class is the set of member functions—usually in a related CPP file.

4. Public data members can be accessed by clients of the class. Private data members can be accessed only by member functions of the class.

5. Yes, member functions can be private. Although not shown in this chapter, a member function can be private. Only other member functions of the class will be able to use the private function.

6. Although member data can be public, it is good programming practice to make it private and to provide public accessor functions to the data.

7. Yes. Each object of a class has its own data members.

8. Declarations end with a semicolon after the closing brace; function definitions do not.

9. The header for a Cat function, Meow(), that takes no parameters and returns void looks like this:


void Cat::Meow()

10. The constructor is called to initialize a class. This special function has the same name as the class.

Exercises

1. The following is one possible solution:


class Employee
{
    int Age;
    int YearsOfService;
    int Salary;
};

2. The following is one possible answer. Notice that the Get... accessor methods were also made constant because they won’t change anything in the class.


// Employee.hpp
class Employee
{
  public:
      int  GetAge() const;
      void SetAge(int age);
      int  GetYearsOfService() const;
      void SetYearsOfService(int years);
      int  GetSalary() const;
      void SetSalary(int salary);

  private:
      int itsAge;
      int itsYearsOfService;
      int itsSalary;
};

3. The following is one possible solution:

Image

Image

4. The following is one possible answer:


float Employee::GetRoundedThousands() const
{
    return Salary / 1000;
}

5. The following is one possible answer:


class   Employee
{
  public:

    Employee(int age, int years, int salary);
      int  GetAge() const;
      void SetAge(int age);
      int  GetYearsOfService() const;
      void SetYearsOfService(int years);
      int  GetSalary() const;
      void SetSalary(int salary);

  private:
      int itsAge;
      int itsYearsOfService;
      int itsSalary;
};

6. Class declarations must end with a semicolon.

7. The accessor GetAge() is private. Remember: All class members are private unless you say otherwise.

8. You can’t access itsStation directly. It is private.

You can’t call SetStation() on the class. You can call SetStation() only on objects.

You can’t initialize myOtherTV because there is no matching constructor.

Day 7

Quiz

1.Separate the initializations with commas, such as


for (x = 0, y = 10; x < 100; x++, y++).

2.goto jumps in any direction to any arbitrary line of code. This makes for source code that is difficult to understand and, therefore, difficult to maintain.

3.Yes, if the condition is false after the initialization, the body of the for loop will never execute. Here’s an example:


for (int x = 100; x < 100; x++)

4.The variable x is out of scope; thus, it has no valid value.

5.Yes. Any loop can be nested within any other loop.

6.Yes. Following are examples for both a for loop and a while loop:


for(;;)
{
    // This for loop never ends!
}
while(true)
{
    // This while loop never ends!
}

7. Your program appears to “hang” because it never quits running. This causes you to have to reboot the computer or to use advanced features of your operating system to end the task.

Exercises

1.The following is one possible answer:


for (int i = 0; i< 10; i++)
{
    for ( int j = 0; j< 10; j++)
       cout << "0";
    cout << endl;
}

2.The following is one possible answer:


for (int x = 100; x<=200; x+=2)

3.The following is one possible answer:


int x = 100;
while (x <= 200)
    x+= 2;

4.The following is one possible answer:


int x = 100;
do
{
    x+=2;
} while (x <= 200);

5.counter is never incremented and the while loop will never terminate.

6.There is a semicolon after the loop and the loop does nothing. The programmer might have intended this, but if counter was supposed to print each value, it won’t. Rather, it will only print out the value of the counter after the for loop has completed.

7.counter is initialized to 100, but the test condition is that if it is less than 10, the test will fail and the body will never be executed. If line 1 were changed to int counter = 5;, the loop would not terminate until it had counted down past the smallest possible int. Because int is signed by default, this would not be what was intended.

8.Case 0 probably needs a break statement. If not, it should be documented with a comment.

Day 8

Quiz

1.The address-of operator (&) is used to determine the address of any variable.

2.The dereference operator (*) is used to access the value at an address in a pointer.

3.A pointer is a variable that holds the address of another variable.

4.The address stored in the pointer is the address of another variable. The value stored at that address is any value stored in any variable. The indirection operator (*) returns the value stored at the address, which itself is stored in the pointer.

5.The indirection operator returns the value at the address stored in a pointer. The address-of operator (&) returns the memory address of the variable.

6.The const int * ptrOne declares that ptrOne is a pointer to a constant integer.

The integer itself cannot be changed using this pointer.

The int * const ptrTwo declares that ptrTwo is a constant pointer to integer. After it is initialized, this pointer cannot be reassigned.

Exercises

1.

a. int * pOne; declares a pointer to an integer.

b. int vTwo; declares an integer variable.

c. int * pThree = &vTwo; declares a pointer to an integer and initializes it with the address of another variable, vTwo.

2.unsigned short *pAge = &yourAge;

3.*pAge = 50;

4.The following is one possible answer:

Image

5.pInt should have been initialized. More importantly, because it was not initialized and was not assigned the address of any memory, it points to a random place in memory. Assigning a literal (9) to that random place is a dangerous bug.

6.Presumably, the programmer meant to assign 9 to the value at pVar, which would be an assignment to SomeVariable. Unfortunately, 9 was assigned to be the value of pVar because the indirection operator (*) was left off. This will lead to disaster if pVar is used to assign a value because it is pointing to whatever is at the address of 9 and not at SomeVariable.

Day 9

Quiz

1.A reference is an alias, and a pointer is a variable that holds an address. References cannot be null and cannot be assigned to.

2.When you need to reassign what is pointed to, or when the pointer might be null.

3.A null pointer (0).

4.This is a shorthand way of saying a reference to a constant object.

5.Passing by reference means not making a local copy. It can be accomplished by passing a reference or by passing a pointer.

6.All three are correct; however, you should pick one style and then use it consistently.

Exercises

1.The following is one possible answer:

Image

2.The following is one possible answer.


1:  int main()
2:  {
3:     int varOne;
4:     const int * const pVar = &varOne;
5:     varOne = 6;
6:     *pVar = 7;
7:     int varTwo;
8:     pVar = &varTwo;
9:     return 0;
10:  }

3.You can’t assign a value to a constant object, and you can’t reassign a constant pointer. This means that lines 6 and 8 are problems.

4.The following is one possible answer. Note that this is a dangerous program to run because of the stray pointer.


1:  int main()
2:  {
3:     int * pVar;
4:     *pVar = 9;
5:     return 0;
6:  }

5.The following is one possible answer:


1:  int main()
2:  {
3:     int VarOne;
4:     int * pVar = &varOne;
5:     *pVar = 9;
6:     return 0;
7:  }

6.The following is one possible answer. Note that you should avoid memory leaks in your programs.

Image

7.The following is one possible answer:


1:  #include <iostream>
2:  void FuncOne();
3:  int main()
4:  {
5:     FuncOne();
6:     return 0;
7:  }
8:
9:  void FuncOne()
10:  {
11:     int * pVar = new int (5);
12:     std::cout << "The value of *pVar is: " << *pVar ;
13:     delete pVar;
14:  }

8.MakeCat returns a reference to the CAT created on the free store. There is no way to free that memory, and this produces a memory leak.

9.The following is one possible answer:

Image

Day 10

Quiz

1.Overloaded member functions are functions in a class that share a name but differ in the number or type of their parameters.

2.A definition sets aside memory; a declaration does not. Almost all declarations are definitions; the major exceptions are class declarations, function prototypes, and typedef statements.

3.Whenever a temporary copy of an object is created. This also happens every time an object is passed by value.

4.The destructor is called each time an object is destroyed, either because it goes out of scope or because you call delete on a pointer pointing to it.

5.The assignment operator acts on an existing object; the copy constructor creates a new one.

6.The this pointer is a hidden parameter in every member function that points to the object itself.

7.The prefix operator takes no parameters. The postfix operator takes a single int parameter, which is used as a signal to the compiler that this is the postfix variant.

8.No, you cannot overload any operator for built-in types.

9.It is legal, but it is a bad idea. Operators should be overloaded in a way that is likely to be readily understood by anyone reading your code.

10.None. Like constructors and destructors, they have no return values.

Exercises

1.The following is one possible answer:


class SimpleCircle
{
   public:
     SimpleCircle();
     ~SimpleCircle();
     void SetRadius(int);
     int GetRadius();
   private:
     int itsRadius;
};

2.The following is one possible answer:


SimpleCircle::SimpleCircle():
itsRadius(5)
{}

3.The following is one possible answer:


SimpleCircle::SimpleCircle(int radius):
itsRadius(radius)
{}

4.The following is one possible answer:


const SimpleCircle& SimpleCircle::operator++()
{
     ++(itsRadius);
     return *this;
}

// Operator ++(int) postfix.
// Fetch then increment
const SimpleCircle SimpleCircle::operator++ (int)
{
    // declare local SimpleCircle and initialize to value of *this
    SimpleCircle temp(*this);
    ++(itsRadius);
    return temp;
}

5.The following is one possible answer:

Image

6.The following is one possible answer:


SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
        int val = rhs.GetRadius();
        itsRadius = new int(val);
}

7.The following is one possible answer:


SimpleCircle& SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if (this == &rhs)
        return *this;
    delete itsRadius;
    itsRadius = new int;
    *itsRadius = rhs.GetRadius();
    return *this;
}

8.The following is one possible answer:

Image

Image

9.You must check to see whether rhs equals this, or the call to a = a will crash your program.

10.This operator+ is changing the value in one of the operands, rather than creating a new VeryShort object with the sum. The correct way to do this is as follows:


VeryShort  VeryShort::operator+ (const VeryShort& rhs)
{
   return VeryShort(itsVal + rhs.GetItsVal());
}

Day 11

Quiz

1.Procedural programming focuses on functions separate from data. Object-oriented programming ties data and functionality together into objects, and focuses on the interaction among the objects.

2.The phases of object-oriented analysis and design include conceptualization, which is the single sentence that describes the great idea; analysis, which is the process of understanding the requirements; and design, which is the process of creating the model of your classes, from which you will generate your code.

These are followed by implementation, testing, and rollout.

3.Encapsulation refers to the (desirable) trait of bringing together in one class all the data and functionality of one discrete entity.

4.A domain is an area of the business for which you are creating a product.

5.An actor is any person or system that is external to the system you are developing and interacts with the system you are developing.

6.A use case is a description of how the software will be used. It is a description of an interaction between an actor and the system itself.

7.A is true and B is not.

Exercises

1.The following diagram provides one possible answer:

Image

2.Cars, motorcycles, trucks, bicycles, pedestrians, and emergency vehicles all use the intersection. In addition, there is a traffic signal with Walk/Don’t Walk lights.

Should the road surface be included in the simulation? Certainly, road quality can have an effect on the traffic, but for a first design, it might be simpler to leave this consideration aside.

The first object is probably the intersection itself. Perhaps the intersection object maintains lists of cars waiting to pass through the signal in each direction, as well as lists of people waiting to cross at the crosswalks. It will need methods to choose which and how many cars and people go through the intersection.

There will only be one intersection, so you might want to consider how you will ensure that only one object is instantiated. (Hint: Think about static methods and protected access.)

People and cars are both clients of the intersection. They share a number of characteristics: They can appear at any time, there can be any number of them, and they both wait at the signal (although in different lines). This suggests that you will want to consider a common base class for pedestrians and cars.

The classes could, therefore, include the following:


class Entity;          // a client of the intersection
class Vehicle : Entity ...;          // the root of all cars, trucks, bicycles and emergency vehicles.
class Pedestrian : Entity...;   // the root of all People
class Car : public Vehicle...;
class Truck : public Vehicle...;
class Motorcycle : public Vehicle...;
class Bicycle : public Vehicle...;
class Emergency_Vehicle : public Vehicle...;
class Intersection;          // contains lists of cars and people waiting to pass

3.Two discrete programs could be written for this project: the client, which the users run, and the server, which would run on a separate machine. In addition, the client machine would have an administrative component to enable a system administrator to add new people and rooms.

If you decide to implement this as a client/server model, the client would accept input from users and generate a request to the server. The server would service the request and send back the results to the client. With this model, many people can schedule meetings at the same time.

On the client’s side, there are two major subsystems in addition to the administrative module: the user interface and the communications subsystem. The server’s side consists of three main subsystems: communications, scheduling, and a mail interface, which would announce to the user when changes have occurred in the schedule.

4.A meeting is defined as a group of people reserving a room for a certain amount of time. The person making the schedule might desire a specific room, or a specified time; however, the scheduler must always be told how long the meeting will last and who is required.

The objects will probably include the users of the system as well as the conference rooms. Remember to include classes for the calendar, and perhaps a class Meeting that encapsulates all that is known about a particular event.

The prototypes for the classes might include

Image

Image

You might have used private instead of protected. Protected members are covered on Day 12, “Implementing Inheritance.”

Day 12

Quiz

1.A v-table, or virtual function table, is a common way for compilers to manage virtual functions in C++. The table keeps a list of the addresses of all the virtual functions, and depending on the runtime type of the object pointed to, invokes the right function.

2.A destructor of any class can be declared to be virtual. When the pointer is deleted, the runtime type of the object will be assessed and the correct derived destructor invoked.

3.This was a trick question—there are no virtual constructors.

4.By creating a virtual method in your class, which itself calls the copy constructor.

5.Base::FunctionName();

6.FunctionName();

7.Yes, the virtuality is inherited and cannot be turned off.

8.protected members are accessible to the member functions of derived objects.

Exercises

1.virtual void SomeFunction(int);

2.Because you are showing a declaration of Square, you don’t need to worry about Shape. Shape is automatically included as a part of Rectangle.


class Square : public Rectangle
{};

3.Just as with Exercise 2, you don’t need to worry about Shape.


Square::Square(int length):
     Rectangle(length, width){}

4.The following is one possible answer:


class Square
{
   public:
      // ...
      virtual Square * clone() const { return new Square(*this); }
       // ...
};

5.Perhaps nothing. SomeFunction expects a Shape object. You’ve passed it a Rectangle “sliced” down to a Shape. As long as you don’t need any of the Rectangle parts, this will be fine. If you do need the Rectangle parts, you’ll need to change SomeFunction to take a pointer or a reference to a Shape.

6.You can’t declare a copy constructor to be virtual.

Day 13

Quiz

1.SomeArray[0], SomeArray[24]

2.Write a set of subscripts for each dimension. For example, SomeArray[2][3][2] is a three-dimensional array. The first dimension has two elements, the second has three, and the third has two.

3.SomeArray[2][3][2] = { { {1,2},{3,4},{5,6} } , { {7,8},{9,10},{11,12} } };

4.10*5*20=1,000

5.Both arrays and linked lists are containers for storing information; however, linked lists are designed to link together as needed.

6.This string contains 16 characters—the fifteen you see and the null character that ends the string.

7.The null character.

Exercises

1.The following is one possible solution. Your array might have a different name, but should be followed by [3][3] in order to hold a 3 by 3 board.


int GameBoard[3][3];

2.int GameBoard[3][3] = { {0,0,0},{0,0,0},{0,0,0} }

3.The following is one possible solution. This uses the strcpy() and strlen() functions.


#include <iostream>
#include <cstring>
using namespace std;

int main()
{
   char firstname[] = "Alfred";
   char middlename[] = "E";
   char lastname[] = "Numan";
   char fullname[80];
   int  offset = 0;

   strcpy(fullname,firstname);
   offset = strlen(firstname);
   strcpy(fullname+offset," ");
   offset += 1;
   strcpy(fullname+offset,middlename);
   offset += strlen(middlename);
   strcpy(fullname+offset,". ");
   offset += 2;
   strcpy(fullname+offset,lastname);

   cout << firstname << "-" << middlename << "-"
        << lastname << endl;
   cout << "Fullname: " << fullname << endl;

   return 0;
}

4.The array is five elements by four elements, but the code initializes 4×5.

5.You wanted to write i<5, but you wrote i<=5 instead. The code will run when i == 5 and j == 4, but there is no such element as SomeArray[5][4].

Day 14

Quiz

1.A down cast (also called “casting down”) is a declaration that a pointer to a base class is to be treated as a pointer to a derived class.

2.This refers to the idea of moving shared functionality upward into a common base class. If more than one class shares a function, it is desirable to find a common base class in which that function can be stored.

3.If neither class inherits using the keyword virtual, two Shapes are created, one for Rectangle and one for Shape. If the keyword virtual is used for both classes, only one shared Shape is created.

4.Both Horse and Bird initialize their base class, Animal, in their constructors. Pegasus does as well, and when a Pegasus is created, the Horse and Bird initializations of Animal are ignored.

5.The following is one possible answer:


class Vehicle
{
     virtual void Move() = 0;
}

6.None must be overridden unless you want to make the class nonabstract, in which case all three must be overridden.

Exercises

1.class JetPlane : public Rocket, public Airplane

2.class Seven47: public JetPlane

3.The following is one possible answer:

Image

4.The following is one possible answer:

Image

Day 15

Quiz

1.Yes. They are member variables and their access can be controlled like any other. If they are private, they can be accessed only by using member functions or, more commonly, static member functions.

2.static int itsStatic;

3.static int SomeFunction();

4.long (* function)(int);

5.long ( Car::*function)(int);

6.long ( Car::*function)(int) theArray [10];

Exercises

1.The following is one possible answer:

Image

2.The following is one possible answer:

Image

Image

3.The following is one possible answer:

Image

Image

4.The following is one possible answer:

Image

Image

5.The following is one possible answer:

Image

Image

Image

Day 16

Quiz

1.An is-a relationship is established with public inheritance.

2.A has-a relationship is established with aggregation (containment); that is, one class has a member that is an object of another type.

3.Aggregation describes the idea of one class having a data member that is an object of another type. Delegation expresses the idea that one class uses another class to accomplish a task or goal.

4.Delegation expresses the idea that one class uses another class to accomplish a task or goal. Implemented in terms of expresses the idea of inheriting implementation from another class.

5.A friend function is a function declared to have access to the protected and private members of your class.

6.A friend class is a class declared so that all of its member functions are friend functions of your class.

7.No, friendship is not commutative.

8.No, friendship is not inherited.

9.No, friendship is not associative.

10.A declaration for a friend function can appear anywhere within the class declaration. It makes no difference whether you put the declaration within the public:, protected:, or private: access areas.

Exercises

1.The following is one possible answer:


class Animal:
{
   private:
      String itsName;
};

2.The following is one possible answer:


class boundedArray : public Array
{
   //...
}

3.The following is one possible answer:


class Set : private Array
{
   // ...
}

4.The following is one possible answer:

Image

Image

5.You can’t put the friend declaration into the function. You must declare the function to be a friend in the class.

6.The following is the fixed listing:

Image

7.The function setValue(Animal&,int) was declared to be a friend, but the overloaded function setValue(Animal&,int,int) was not declared to be a friend.

8.The following is the fixed listing:

Image

Day 17

Quiz

1.The insertion operator (<<) is a member operator of the ostream object and is used for writing to the output device.

2.The extraction operator (>>) is a member operator of the istream object and is used for writing to your program’s variables.

3.The first form of get() is without parameters. This returns the value of the character found, and will return EOF (end of file) if the end of the file is reached.

The second form of get() takes a character reference as its parameter; that character is filled with the next character in the input stream. The return value is an iostream object.

The third form of get() takes an array, a maximum number of characters to get, and a terminating character. This form of get() fills the array with up to one fewer characters than the maximum (appending null) unless it reads the terminating character, in which case it immediately writes a null and leaves the terminating character in the buffer.

4.cin.read() is used for reading binary data structures.

getline() is used to read from the istream’s buffer.

5.Wide enough to display the entire number.

6.A reference to an istream object.

7.The filename to be opened.

8.ios::ate places you at the end of the file, but you can write data anywhere in the file.

Exercises

1.The following is one possible solution:


0:   // Ex1701.cpp
1:   #include <iostream>
2:   int main()
3:   {
4:        int x;
5:        std::cout << "Enter a number: ";
6:        std::cin >> x;
7:        std::cout << "You entered: " << x << std::endl;
8:        std::cerr << "Uh oh, this to cerr!" << std::endl;
9:        std::clog << "Uh oh, this to clog!" << std::endl;
10:        return 0;
11:   }

2.The following is one possible solution:


0:    // Ex1702.cpp
1:    #include <iostream>
2:    int main()
3:    {
4:       char name[80];
5:       std::cout << "Enter your full name: ";
6:       std::cin.getline(name,80);
7:       std::cout << " You entered: " << name << std::endl;
8:       return 0;
9:    }

3.The following is one possible solution:

Image

4.The following is one possible solution:

Image

5.The following is one possible solution:

Image

Day 18

Quiz

1.Outer::Inner::MyFunc();

2.At the point the listing reaches HERE, the global version of X will be used, so it will be 4.

3.Yes, you can use names defined in a namespace by prefixing them with the namespace qualifier.

4.Names in a normal namespace can be used outside of the translation unit where the namespace is declared. Names in an unnamed namespace can only be used within the translation unit where the namespace is declared.

5.The using keyword can be used for the using directives and the using declarations. A using directive allows all names in a namespace to be used as if they are normal names. A using declaration, on the other hand, enables the program to use an individual name from a namespace without qualifying it with the namespace qualifier.

6.Unnamed namespaces are namespaces without names. They are used to wrap a collection of declarations against possible name clashes. Names in an unnamed namespace cannot be used outside of the translation unit where the namespace is declared.

7.The standard namespace std is defined by the C++ Standard Library. It includes declarations of all names in the Standard Library.

Exercises

1.The C++ standard iostream header file declares cout and endl in namespace std. They cannot be used outside of the standard namespace std without a namespace qualifier.

2.You can add the following line between lines 0 and 1.

      using namespace std;

You can add the following two lines between 0 and 1:


using std::cout;
      using std::endl;

You can change line 3 to the following:

std::cout << "Hello world!" << std::endl;

3.The following is one possible answer:


Namespace MyStuff
{
   class MyClass
   {
      //MyClass stuff
   }
}

Day 19

Quiz

1.Templates are built in to the C++ language and are type-safe. Macros are implemented by the preprocessor and are not type-safe.

2.The parameter to the template creates an instance of the template for each type. If you create six template instances, six different classes or functions are created. The parameters to the function change the behavior or data of the function, but only one function is created.

3.The general template friend function creates one function for every type of the parameterized class; the type-specific function creates a type-specific instance for each instance of the parameterized class.

4.Yes, create a specialized function for the particular instance. In addition to creating Array<t>::SomeFunction(), also create Array<int>::SomeFunction() to change the behavior for integer arrays.

5.One for each instance type of the class.

6.The class must define a default constructor, a copy constructor, and an overloaded assignment operator.

7.STL stands for the Standard Template Library. This library is important because it contains a number of template classes that have already been created and are ready for you to use. Because these are a part of the C++ standard, any compiler supporting the standard will also support these classes. This means you don’t have to “reinvent the wheel!”

Exercises

1.One way to implement this template:

Image

2.The following is one possible answer:

Image

3.The following is one possible answer:

Image

Image

4.The following declare the three objects:


List<String> string_list;
List<Cat> Cat_List;
List<int> int_List;

5.Cat doesn’t have operator == defined; all operations that compare the values in the List cells, such as is_present, will result in compiler errors. To reduce the chance of this, put copious comments before the template definition stating what operations must be defined for the instantiation to compile.

6.The following is one possible answer:


friend int operator==( const Type& lhs, const Type& rhs );

7.The following is one possible answer:

Image

8.Yes, because comparing the array involves comparing the elements, operator!= must be defined for the elements as well.

9.The following is one possible answer:


0:  // Exercise 19.9
1:  // template swap:
2:  // must have assignment and the copy constructor defined for the Type.
3:  template <class Type>
4:  void swap( Type& lhs, Type& rhs)
5:  {
6:       Type temp( lhs );
7:       lhs = rhs;
8:       rhs = temp;
9:  }

Day 20

Quiz

1.An exception is an object that is created as a result of invoking the keyword throw. It is used to signal an exceptional condition, and is passed up the call stack to the first catch statement that handles its type.

2.A try block is a set of statements that might generate an exception.

3.A catch statement is a routine that has a signature of the type of exception it handles. It follows a try block and acts as the receiver of exceptions raised within the try block.

4.An exception is an object and can contain any information that can be defined within a user-created class.

5.Exception objects are created when the program invokes the keyword throw.

6.In general, exceptions should be passed by reference. If you don’t intend to modify the contents of the exception object, you should pass a const reference.

7.Yes, if you pass the exception by reference.

8.catch statements are examined in the order they appear in the source code. The first catch statement whose signature matches the exception is used. In general, it is best to start with the most specific exception and work toward the most general.

9.catch(...) catches any exception of any type.

10.A breakpoint is a place in the code where the debugger stops execution.

Exercises

1.The following is one possible answer:

Image

2.The following is one possible answer:

Image

3.The following is one possible answer:

Image

Image

Image

4.The following is one possible answer:

Image

Image

Image

5.In the process of handling an “out of memory” condition, a string object is created by the constructor of xOutOfMemory. This exception can only be raised when the program is out of memory, and so this allocation must fail.

It is possible that trying to create this string will raise the same exception, creating an infinite loop until the program crashes. If this string is really required, you can allocate the space in a static buffer before beginning the program, and then use it as needed when the exception is thrown.

You can test this program by changing the line if (var == 0) to if (1), which forces the exception to be thrown.

Day 21

Quiz

1.Inclusion guards are used to protect a header file from being included into a program more than once.

2.This quiz question must be answered by you, depending on the compiler you are using.

3.#define debug 0 defines the term debug to equal 0 (zero). Everywhere the word “debug” is found, the character 0 is substituted. #undef debug removes any definition of debug; when the word debug is found in the file, it is left unchanged.

4.The answer is 4 / 2, which is 2.

5.The result is 10 + 10 / 2, which is 10 + 5, or 15. This is obviously not the result desired.

6.You should add parentheses:


HALVE (x) ((x)/2)

7.Two bytes is 16 bits, so up to 16 bit values could be stored.

8.Five bits can hold 32 values (0 to 31).

9.The result is 1111 1111.

10.The result is 0011 1100.

Exercises

1.The inclusion guard statements for the header file STRING.H would be:


#ifndef STRING_H
#define STRING_H
...
#endif

2.The following is one possible answer:

Image

3.The following is one possible answer:


#ifndef DEBUG
#define DPRINT(string)
#else
#define DPRINT(STRING) cout << #STRING ;
#endif

4.The following is one possible answer:


class myDate
{
  public:
    // stuff here...
  private:
    unsigned int Month : 4;
    unsigned int Day   : 8;
    unsigned int Year  : 12;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.79.84