Reputation: 2159
New to C++ and working on a personal project, but having issues passing by reference with a vector list.
I need a function I can call to add a user to a running vector list of users. Where the first parameter is the list I'm adding to (by reference) and the second being the name of the new user.
Maybe my understanding of lvalues and rvalues are wrong... but how is user_list not an lvalue? It's explicitly defined above?
Error I'm getting is:
error: invalid initialization of non-const reference of type 'std::vector<User*>&' from an rvalue of type 'std::vector<User*>*'
User *current_user = add_user(&user_list, "Default User");
^
..\src\main.cpp:8:7: error: in passing argument 1 of 'User* add_user(std::vector<User*>&, std::string)'
User *add_user(vector<User *> &user_list, string name);
Code in Question:
#include <iostream>
#include <vector>
#include "User.h"
using namespace std;
User *add_user(vector<User *> &user_list, string name);
int main() {
vector<User *> user_list;
User *current_user = add_user(&user_list, "Default User");
cout << current_user->name;
current_user->add_friend(new User("Second"));
return 0;
}
User *add_user(vector<User *> &user_list, string name) {
user_list.push_back(new User(name));
return user_list.at(user_list.end());
}
Upvotes: 2
Views: 1100
Reputation: 103713
user_list
is an lvalue. &user_list
is not. It's also the wrong type. If you examine your error message closely, you will notice an extra asterisk at the end of the type. You are passing a pointer (std::vector<User*>*
) to a function that expects a reference (std::vector<User*>&
). Just drop the &
.
User *current_user = add_user(user_list, "Default User");
Upvotes: 3
Reputation: 6039
Your function signature is to pass by reference the user list. You are passing the address of the vector
when you call add_user
. Get rid of the & on the vector in the function call and you should be OK.
Also, don't forget to delete
the memory you new
in the add_friend
call and the memory you new
in the push_back
call.
Upvotes: 1