-2

I'm having problems figuring out if i should use pointers or references in certain methods

I have a method called issueOrders(Orders* order) which takes a reference to an Orders object

This method should add the pointer to order to a vector containing pointers to orders

void Player::issueOrder(Orders* order)
{
    ordersList->getOrdersList().push_back(order);
}

where ordersList is an object containing a vector of ordersList as parameter

Like this:

class OrdersList{
private : 
  vector<Orders*> ordersList
public:
vector<Orders*> getOrdersList();
}

But the issueOrders method doesnt work, that is, nothing is pushed in the vector and im confused as to why.

Thanks for reading and any help is appreciated! :)

  • Is `ordersList` a pointer? If not, you should access its members with the `.` notation – sode Nov 06 '21 at 23:45
  • 7
    `vector getOrdersList();` returns a *copy* of the vector, so you are then calling `push_back` on that copy (which is discarded right afterwards) – UnholySheep Nov 06 '21 at 23:47
  • The default answer to "Should I use raw pointers?" is no. There are no references in your code. – Retired Ninja Nov 07 '21 at 00:31
  • It seems you are trying to give access to a private member through pointer redirection, thus making that member exposed. If that's the case, you want to add `friend class Player;` in `OrdersList` class, so `Player` can access `OrdersList`'s members directly. – Barmak Shemirani Nov 07 '21 at 01:43

1 Answers1

2

As @UnholySheep pointed out, your getter returns a copy of the ordersList vector. What you want is a reference (or a pointer), so that your push_backs affect the vector. So you want to change its declaration to this:

vector<Orders*>& getOrdersList();

And change its definition accordingly.

Whether or not you should store your Orders as pointers or references has nothing to do with the problem. And as the correct answer to the question in your title is largely dependent on the type of the data and the way it's going to be used, it's hard to give you an answer with just the code snippets. I suggest you take a look at this answer: https://stackoverflow.com/a/8259173/13191576

Titus
  • 72
  • 7