Pass entire vector of objects to constructor by reference?

Started by
6 comments, last by Eck 10 years, 2 months ago

I am needing to pass an entire vector of objects to a constructor of another class. I have succeeded in doing this with a single vector object, but with the entire vector, it's giving me trouble.

Here is the code.

classes.h:


 
class Star: public Spell
{
     public:
          Star(std::vector<Hero>& hero_list): h_list(hero_list) {}
     protected:
          std::vector<Hero>& h_list;
}
 

spells.cpp:


 
Star::Star(std::vector<Hero>& hero_list): h_list(hero_list)
{
 
}
 

and then the call from main.cpp:


 
std::vector<Spell*> spells;
spells.push_back(new Star(*heroes));
 

Right now, it's not liking the call. I get: "Error: no operator "*" matches these operands"

I have similar code that is working just fine with passing a single object from the vector, but not this.

I need to pass the entire vector for this particular spell sub-class so it can check values of multiple hero objects and make changes to them.

Advertisement

I'm going to assume that your variable heroes is not a pointer, in which case you should not use the * operator and just pass it directly to the constructor: spells.push_back(new Star(heroes));

It works for your single objects since they are pointers.

That isnt working either : ( Thank you though. Im so confused!

What is the type of the heroes object? Your compiler is complaining about you using operator* on heroes.

Yo dawg, don't even trip.

Oh yeah, the declaration of the heroes vector is

std::vector<Hero*> heroes;

The vectors have incompatible types. Spell constructor is expecting std::vector<Hero>& and what you're giving it is... actually you're trying to perform an invalid operation on heroes so I'm not really sure what to say in this case.

There's a two main ways to go here. A) you change the std::vector<Hero>& inside of Spell to std::vector<Hero*>& and then change the push_back call to what Pachanoi said, or B) you change the type of std::vector<Hero*> to std::vector<Hero> and still change the push_back call to what Pachanoi said biggrin.png That will probably solve the problem.

You might want to review the syntax for using pointers and references though to fully understand how to pass them to functions.

Yo dawg, don't even trip.

Thank you so much! It hit me after you asked what the type was. Pointers and references do still confuse me a bit but I am trying! Thanks for the help!

Don't feel bad. Pointers are one of those things most people have problems with at first. Keep messing with them, and it will eventually "click". And then you'll wonder to yourself, "Why the heck did I think that was so hard?" :)

- Eck

EckTech Games - Games and Unity Assets I'm working on
Still Flying - My GameDev journal
The Shilwulf Dynasty - Campaign notes for my Rogue Trader RPG

This topic is closed to new replies.

Advertisement