Re: declare a class pointer
On 1 Mai, 08:58, Mike wrote:
Hi
how do i declare a class pointer?
like any other pointer:
myclass* pointer_variable;
int * drops[] = new droplet(int, int, int); // WRONG
Yes, there's a lot wrong with it. In fact, there's so much wrong with
it, that I don't know what you were trying to do. (hint hint)
--------- // later
class droplet
{
public:
int trail[16];//information on all characters
int speed;//speed, 1, 2 or 3.
int X, Y;
droplet(int x, int y, int spd);
~droplet();
...
If you don't need a custom destructor, just don't declare/define it.
--------later i call it alike:
for(int dDrops=0;dDrops<num;dDrops++)
{
drops[dDrops] = new droplet(...
So, you want "drops" to be some kind of "array" which stores pointers
to droplet objects. Seeing that you have trouble expressing C++
programs chances are that this isn't a good design approach. So, you
might want to consider various approaches with their varying
properties:
1. "Fixed array" of droplet-pointers
droplet* drops[num]; // num needs to be a compile-time constant
for (int i=0; i<num; ++i)
drops[i] = new droplet(1,2,3);
...
for (int i=0; i<num; ++i)
delete drops[i];
2. Dynamically-allocated array of droplet pointers:
droplet** drops = new droplet*[num];
for (int i=0; i<num; ++i)
drops[i] = new droplet(1,2,3);
...
for (int i=0; i<num; ++i)
delete drops[i];
delete[] drops;
3. "Dynamic array" of droplet pointers
std::vector<droplet*> drops;
for (int i=0; i<num; ++i)
drops.push_back(new droplet(1,2,3));
...
for (int i=0; i<num; ++i)
delete drops.at(i);
4. "Dynamic array" of droplets
std::vector<droplet> drops;
for (int i=0; i<num; ++i)
drops.push_back(droplet(1,2,3));
I included the necessary "clean up" code after the "...". In the last
case there is no need to do anything special in terms of cleaning up.
The std::vector manages its own droplet copies automatically. Note
that I didn't use any new-expression in the last case. You should try
to delegate things like dynamic memory management to "smart" objects
like std::vector. Note also, that in the 3rd case the vector stores
pointers. In the vector's destructor the pointers are correctly
destroyed but not those objects they point to which is why there's a
loop over all pointers after "..." to delete those objects. Another
thing I'd like to mention is that only approach 4 is exception-safe in
the sense that if an exception is thrown somewhere during the droplet
particle creation (unlikely) or during the "..." you'll get memory
leaks.
You are likely to get better answers if you describe what you are
trying to do (not how).
Cheers,
SG