|
.gif)
One
or more of the data members of a class can be a
pointer to an object on the free store. The memory
can be allocated in the class constructor or in
one of its methods, and it can be deleted in its
destructor, as Listing 8.7 illustrates.
Listing
8.7. Pointers as member data.
1:
// Listing 8.7
2:
// Pointers as data members
3:
4:
#include <iostream.h>
5:
6:
class SimpleCat
7:
{
8:
public:
9:
SimpleCat();
10:
~SimpleCat();
11:
int GetAge() const { return *itsAge; }
12:
void SetAge(int age) { *itsAge = age; }
13:
14:
int GetWeight() const { return *itsWeight; }
15:
void setWeight (int weight) { *itsWeight = weight;
}
16:
17:
private:
18:
int * itsAge;
19:
int * itsWeight;
20:
};
21:
22:
SimpleCat::SimpleCat()
23:
{
24:
itsAge = new int(2);
25:
itsWeight = new int(5);
26:
}
27:
28:
SimpleCat::~SimpleCat()
29:
{
30:
delete itsAge;
31:
delete itsWeight;
32:
}
33:
34:
int main()
35:
{
36:
SimpleCat *Frisky = new SimpleCat;
37:
cout << "Frisky is " << Frisky->GetAge()
<< " years old\n";
38:
Frisky->SetAge(5);
39:
cout << "Frisky is " << Frisky->GetAge()
<< " years old\n";
40:
delete Frisky;
41:
return 0;
42:
}
Output:
Frisky is 2 years old
Frisky is 5 years old
Analysis: The class SimpleCat is declared
to have two member variables—both of which are pointers
to integers—on lines 14 and 15. The constructor
(lines 22-26) initializes the pointers to memory
on the free store and to the default values. The
destructor (lines 28-32) cleans up the allocated
memory. Because this is the destructor, there is
no point in assigning these pointers to null, as
they will no longer be accessible. This is one of
the safe places to break the rule that deleted pointers
should be assigned to null, although following the
rule doesn’t hurt.
The
calling function (in this case, main()) is unaware
that itsAge and itsWeight are point-ers to memory
on the free store. main() continues to call GetAge()
and SetAge(), and the details of the memory management
are hidden in the implementation of the class—as
they should be.
When
Frisky is deleted in line 40, its destructor is
called. The destructor deletes each of its member
pointers. If these, in turn, point to objects of
other user-defined classes, their destructors are
called as well.
|