Hey,
I was wondering if this method of using an array should be avoided:
Code:
class Get
{
int itsNum;
public:
Get(int num) : itsNum(num) {}
int GetNum() { return itsNum; }
};
int main()
{
Get* Array[500];
int i;
for(i = 0; i < 500; i++) {
Array[i] = new Get(i);
}
for(i = 0; i < 500; i++) {
cout << Array[i]->GetNum();
}
for(i = 0; i < 500; i++) {
delete Array[i];
}
cin.get();
}
The reason I ask is because the tutorials and book I've read dont even consider to mention this. Usually indirect methods are taken, for example creating another pointer to the class, then allocating the space for that class, then pointing 1 of the pointers of the original array of pointers to it. For example:
Code:
5: class CAT
6: {
7: public:
8: CAT() { itsAge = 1; itsWeight=5; }
9: ~CAT() {} // destructor
10: int GetAge() const { return itsAge; }
12: void SetAge(int age) { itsAge = age; }
13:
14: private:
15: int itsAge;
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: }
Code:
5: class CAT
6: {
7: public:
8: CAT() { itsAge = 1; itsWeight=5; }
9: ~CAT();
10: int GetAge() const { return itsAge; }
12: void SetAge(int age) { itsAge = age; }
13:
14: private:
15: int itsAge;
17: };
18:
19: CAT :: ~CAT()
20: {
21: // cout << "Destructor called!\n";
22: }
23:
24: int main()
25: {
26: CAT * Family = new CAT[500];
27: int i;
28: CAT * pCat;
29: for (i = 0; i < 500; i++)
30: {
31: pCat = new CAT;
32: pCat->SetAge(2*i +1);
33: Family[i] = *pCat;
34: delete pCat;
35: }
36:
37: for (i = 0; i < 500; i++)
38: {
38: cout << "Cat #" << i+1 << ": ";
39: cout << Family[i].GetAge() << endl;
40: }
41:
42: delete [] Family;
43:
44: return 0;
45: }
See for that second example why use:
Code:
26: pCat = new CAT;
27: pCat->SetAge(2*i +1);
28: Family[i] = pCat;
instead of:
Code:
26: Family[i] = new CAT;
27: Family[i]->SetAge(2*i +1);
The only reason I can see is so that you can simply delete [], instead of using a delete array like I used. The same thing goes for for the second example, and you can simply delete the array # instead of the copy.
Or for that first example could I use this instead?:
Code:
int i = 0;
Get* Array = new Get[500](i++);
for(i = 0; i < 500; i++) {
cout << "\n" << Array[i].GetNum();
}
delete[] Array;