-
Arrays of Pointers
Will this produce a memory leak?
Code:
#include <iostream.h>
4:
5: class CAT
6: {
7: public:
8: CAT() { itsAge = 1; itsWeight=5; }
9: ~CAT() {} // destructor
10: int GetAge() const { return itsAge; }
11: int GetWeight() const { return itsWeight; }
12: void SetAge(int age) { itsAge = age; }
13:
14: private:
15: int itsAge;
16: int itsWeight;
17: };
18:
19: int main()
20: {
21: CAT * Family[500];
22: int i;
23: CAT * pCat;
24: for (i = 0; i < 500; i++)
25: {
26: pCat = new CAT;
27: pCat->SetAge(2*i +1);
28: Family[i] = pCat;
29: }
30:
31: for (i = 0; i < 500; i++)
32: {
33: cout << "Cat #" << i+1 << ": ";
34: cout << Family[i]->GetAge() << endl;
35: }
36: return 0;
37: }
and mybe I should add folowing lines:
Code:
for (i = 0; i < 500; i++)
{
CAT *p;
p=Family[i];
delete p;
}
-
What's with all the temp variables?
Family[i] = new Cat;
Family[i]->SetAge(2*i +1);
Then, as you surmised a loop doing
delete Family[i];