1
std::vector<Game*> games;

I have the following setter:

void Instructor::setGames(const std::vector<Game *> &value)
{
    games = value;
}

And I am trying to use it like this:

 Game g1, g2, g3;
std::vector <Game> gameSet;
    gameSet.push_back(g1);
    gameSet.push_back(g2);
    gameSet.push_back(g3);
    i.setGames(&gameSet);

But I keep getting this error:

error: no matching function for call to ‘Instructor::setGames(std::vector<Game>*)’
     i.setGames(&gameSet);

This doesn't work either.

 i.setGames(gameSet);

What am I doing wrong? I want to fix this without changing the std::vector<Game*> games;

x89
  • 2,798
  • 5
  • 46
  • 110

2 Answers2

1

Given that you have a vector of Game pointers, that is the type of object it will accept, therefore g1, g2 and g3 must be pointers:

Game *g1, *g2, *g3;
std::vector <Game*> gameSet;

g1 = new Game(); //intialize pointers
g2 = new Game();
g3 = new Game();
//...
i.setGames(gameSet);

Live demo

Note that using raw pointers is not really a good practice these days, it's best to use smart pointers, look into that.

What is a smart pointer and when should I use one?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
0

The

i.setGames(&gameSet);

needs setGames taking pointer to the std::vector<Game>. That means the following function signature

void Instructor::setGames(std::vector<Game> *value);

what you have is const ref to simple std::vector<Game*>

void Instructor::setGames(const std::vector<Game*> &value);

Obviously they are different types and you have the error.


You need simply const std::vector<Game>& value

void Instructor::setGames(const std::vector<Game>& value)
{
    games = value; // also change the type of games  to be std::vector<Game>
}

and in the main

  Game g1, g2, g3;
  std::vector <Game> gameSet{ g1, g2, g3};
  i.setGames(gameSet);
LernerCpp
  • 401
  • 1
  • 5
  • 13
  • Is there no way to fix this without changing ``` std::vector games;``` ? – x89 May 02 '20 at 23:09
  • @FSJ Okay, then the following is the answer. Along with ` i.setGames(gameSet);`. But you don't need ` std::vector`. – LernerCpp May 02 '20 at 23:11