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. 6 6
6. (a) Line 3 is wrong. It should be
Circle c1;
(b) Line 4 is wrong. The object cannot be declared
again.
7. A data field cannot be initialized when it is declared
in C++.
8. The first statement declares an object of Circle. The
object is created using the Circle’s no-arg
constructor.
The second statement is incorrect.
9. The first statement declares an object of Circle. The
object is created using the Circle’s no-arg
constructor.
For the second statement, the left-hand side of the =
sign does the same as the first statement and the
right-hand side creates an anonymous object using the
Circle’s no-arg constructor and copies the object to c.
10. Declare all data fields, constructors, and function
prototypes in the interface and implement functions in
a separate file.
11. (a) output is 5
(b) Output is 8
12. If your program include two header files and one of
which actually include the other, then your program
will receive the multiple declaration error. To prevent
it, use the #ifndef directive.
13. The #define directive defines a constant.
14.
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;
};
15.
You cannot use c.radius, since radius is a private data field.
16. 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).
17. Two benefits: (1) for protecting data and (2) for easy
to maintain the class.
18. Yes.
17.
100000
?
Explanation: Loan’s no-arg constructor is used to initialize loan, but i is not
initialized.