• Advertisement
Sign in to follow this  

Pass entire vector of objects to constructor by reference?

This topic is 1456 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 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. 

Edited by ChainedHollow

Share this post


Link to post
Share on other sites
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.

 

Share this post


Link to post
Share on other sites

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.

Edited by boogyman19946

Share this post


Link to post
Share on other sites

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!

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement