Archived

This topic is now archived and is closed to further replies.

BeanDog

inherited class pointers

Recommended Posts

BeanDog    1065
I have an array of the class enemy, inherited from the class ship. I have a function that accepts a ship* parameter, and it screws up when I try to pass it in my enemy array. Why is this? How do I fix this, short of making copies of the function for each inherited ship class? class enemy : public ship ~BenDilts( void );

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
You''ve found (IMHO) a flaw in the C++ language.

It sounds like your enemy class has some virtual functions and overrides stuff from the ship etc. All this is fine.

But then you try to use an array of these things with a ship pointer. This will get you into trouble. Let''s look at some code:

ship *array = new enemy[10];
array[3].DoSomething(); // Probably fails

Lets say &array[0] = 1000, sizeof(ship)==10, sizeof(enemy)==12. When you say array[3] what the compiler is actually does is "&array[0] + 3 * sizeof(ship)" (1000+3*10 = 1030).

However, this is actually an array of enemies, not ships. 1000 + 3 * sizeof(enemy) = 1036! array[3] ends up looking into the middle of an enemy rather than the start where it should.

I very rarely use arrays of non-trivial objects because there are a lot of cases where things go wrong. This is just one of them.

The easist fix is to make your function act on just one class instead of taking an array of them. You would have to call the function in a loop to cover all of them. You might also look into templates.

-Mike

Share this post


Link to post
Share on other sites
Shannon Barber    1681
Afraid we need more details about what the problem is exactly...

Frankly
ship *array = new enemy[10];
is bad code, and it'd be nice if the compiler at least issued a warning...
enemy* array = new enemy[10];
or
ship** array = new ship*[10];
for(int j=0;j<10;j++)
array[j] = new enemey;
is what you really want


Magmai Kai Holmlor
- The disgruntled & disillusioned


Edited by - Magmai Kai Holmlor on February 1, 2001 10:02:22 PM

Share this post


Link to post
Share on other sites