Advertisement

inherited class pointers

Started by January 31, 2001 04:27 PM
1 comment, last by BeanDog 23 years, 11 months ago
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 );
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
Advertisement
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
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement