language: C++ 4.7.2 (gcc-4.7.2)
date: 716 days 3 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Is there any better way to go about the following?
 
// I need a way to keep track of multiple objects which pop in and out of existence and are all derived from a single base class.
// These objects will be called into existence from multiple functions/methods but the only thing deleting them will the the objects themselves.
 
// This is for a spell system for a game. So I can do this:
 
// A spell is cast, the spell puts itself in an array.
// The game iterates through the array, calling the update() method of any spells in the array
// In the update method there are checks for any collisions or if the spell has been in existence for too long
// if so, the spell removes itself from the array and the game can just continue to iterate through the array like nothing has happened.
 
// I'm asking as I've heard that having objects delete themselves is bad practice and even if we ignore that,
// having to have the array declaration in the middle of the class definition is quite ugly.
 
#include <iostream>
 
class Foo
{
public:
        Foo(int arrayPositionArg)
        {
                arrayPosition = arrayPositionArg;
        }
        void update();
        int arrayPosition;
};
 
const int ARRAY_SIZE = 100;
Foo *array[ARRAY_SIZE];
 
void Foo::update()
{
        if (condition)
        {
                // ...
        }
        else
        {
                array[arrayPosition] = NULL;
                delete this;
        }
}
 
int main (void)
{
        while (bar)
        {
                if (condition)
                {
                        for (int i = 0; i < ARRAY_SIZE; i++)
                        {
                                if (array[i] == NULL)
                                {
                                        array[i] = new Foo(i);
                                        break;
                                }
                        }
                }
 
                for (int i = 0; i < ARRAY_SIZE; i++)
                {
                        array[i]->update();
                }
        }
}
 
prog.cpp: In member function ‘void Foo::update()’:
prog.cpp:34: error: ‘condition’ was not declared in this scope
prog.cpp: In function ‘int main()’:
prog.cpp:47: error: ‘bar’ was not declared in this scope
prog.cpp:49: error: ‘condition’ was not declared in this scope