Passing a derived class object (that is stored in a vector) into a function.

Hello!

I am recreating the classic Asteroids game from my childhood, and have run into a problem. Because of the frame rate, bullets pass through asteroids between frames. To fix this, I have a function that calculates the closest distance between each bullet and rock, called getClosestDistance. To problem I have is that the rocks are stored in a vector of pointers, and the bullets are in a vector of objects. All the classes I have are derived from a FlyingObjects class, so to pass an item of a class that is derived from FlyingObjects into another function, I would simply accept a FlyingObjects. Here is the prototype of getClosestDistanc:

getClosestDistance(FlyingObject &obj1, FlyingObject &obj2)

Theoretically, this is how I should call it, right?

getClosestDistance(rock[i], bullets[i]);

However, I get the compile error:

game.cpp:181:58: error: no matching function for call to ‘Game::getClosestDistance(Rocks*&, Bullet&)’
if (getClosestDistance(rock[i], bullets[i]) < CLOSE_ENOUGH)
^
game.cpp:181:58: note: candidate is:
game.cpp:37:7: note: float Game::getClosestDistance(FlyingObject&, FlyingObject&) const
float Game :: getClosestDistance(FlyingObject &obj1, FlyingObject &obj2) const
^
game.cpp:37:7: note: no known conversion for argument 1 from ‘Rocks*’ to ‘FlyingObject&’

What can I do to fix this? Thanks a billion in advance!

P.S. I gotta go run. Be back soon!
Last edited on
From the error message:
1
2
getClosestDistance(Rocks*&, Bullet&)’
//----------------------^ 

Note the *. You're trying to pass a pointer to a Rocks, while getClosestDistance is expecting a Rocks (not a pointer).

Is your vector of Rocks actually std::vector<Rocks *> rock ?
If so, you need to call getClosestDistance as follows:
 
  getClosestDistance(*rock[i], bullets[i]);


Last edited on
Yes, here is the code for both:

std::vector<Bullet> bullets;
std::vector<Rocks*> rock;

So you are right! It works! Thank you!
Last edited on
Topic archived. No new replies allowed.