x89
x89

Reputation: 3460

how to use a setter for vector of an object

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;

Upvotes: 1

Views: 100

Answers (2)

anastaciu
anastaciu

Reputation: 23822

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?

Upvotes: 1

LernerCpp
LernerCpp

Reputation: 461

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

Upvotes: 0

Related Questions