Jump to content
  • Advertisement


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


inherited class pointers

This topic is 6374 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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.


Share this post

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

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];
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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!