Chapter 9 Objects and Classes

1. See the section "Defining Classes for Objects."

2. Constructors are special kinds of functions that are called when creating an object. Constructors do not have a return type—not even void.

3.  To declare an object using the no-arg constructor, use ClassName objectName;

To declare an object using the constructor with arguments, use ClassName objectName(arguments);

4.  Once an object name is declared, it cannot be reassigned to reference another object. Object names are like constants.

5.  (a) Line 3 is wrong. It should be

Circle c1;

(b) Line 4 is wrong. The object cannot be declared again.

6.  A data field cannot be initialized when it is declared.

7.  Declare all data fields, constructors, and function prototypes in the interface and implement functions in a separate file.

8.  (a) output is 5

(b)  Output is 8

9. 

Implement all the functions in the header file.

class Circle

{

public:

Circle()

{

radius = 1;

};

Circle(double newRadius)

{

radius = newRadius;

}

double getArea()

{

return radius * radius * 3.14159;

};

double getRadius()

{

return radius;

};

void setRadius(double newRadius)

{

radius = newRadius;

};

private:

double radius;

};

10.  (a) Line 4 should be Circle *p = &c1;

(b)  Line 4 should be Circle *p = new Circle()

11.  To create a dynamic object, use the new operator.

To delete an object, use the delete operator.

12. (1) Chicago AtlantaComputer Programming
(2) Chicago AtlantaProgram
(3) Chicago AtlantaNEW
(4) Chicago AtlantaNNN
(5) NNN
(6) Program
(7) NEW
(8) NNN
(9) C
(10) 15
(11) 15
(12) 15
(13) Ccago Atlanta
(14) 0
(15) -1
(16) Chicago Atlanta
(17) ago Atla
(18) ago Atlanta
(19) 8
(20) 11
(21) ChNEWo Atlanta
(22) ChicNEWago Atlanta
(23) ChicagNNNNNNNNo Atlanta
(24) false

13. (1) s1 is empty

(2) have FGHIJKLMN
(3) s1 is Computer Programming

and s2 is I have a dream

14. (1) I

(2) s1 becomes “Computing Programming”

(3) s1 becomes “C++ Computer Programming”

(4) Computer ProgrammingC++

(5) true

(6) true

(7) false

(8) false

(9) false

(10) true

15. Accessor function is for retrieving private data value and mutator function is for changing private data value. The naming convention for accessor function is getDataFieldName() for non-boolean values and isDataFieldName() for bool values. The naming convention for mutator function is setDataFieldName(value).

16. Two benefits: (1) for protecting data and (2) for easy to maintain the class.

17. Yes.

18

// Construct a circle object

Circle::Circle(double radius)

{

this->radius = radius; // or (*this).radius = radius;

}

19.  In C++, you can pass an object to a function by value, by reference, or by reference via a pointer.

20.  myCount.count is 0 times is 0

21.  myCount.count is 100 times is 0

22.  myCount.count is 100 times is 100

23.  string strings[10];

24. 

Atlanta
Dallas