C ++ Forwarding List as a Parameter for a Function

I am trying to create a very simple address book. I created the Contact class, and the address book is a simple list. I am trying to create a function that allows the user to add contacts to the address book. If I take the code outside the function, it will work fine. However, if I insert it, this will not work. I believe that this is a referral transfer versus a transfer on the value problem, which I do not consider as it should. This is the code for the function:

void add_contact(list<Contact> address_book) { //the local variables to be used to create a new Contact string first_name, last_name, tel; cout << "Enter the first name of your contact and press enter: "; cin >> first_name; cout << "Enter the last name of your contact and press enter: "; cin >> last_name; cout << "Enter the telephone number of your contact and press enter: "; cin >> tel; address_book.push_back(Contact(first_name, last_name, tel)); } 

I do not get any errors, however, when I try to display all the contacts, I can only see the original ones.

+8
c ++ list pass-by-reference pass-by-value
source share
4 answers

You pass address_book by value, so a copy of what you pass, and when you leave the scope of add_contact , your changes are lost.

Instead, follow the link:

 void add_contact(list<Contact>& address_book) 
+8
source share

Since you pass a list by value, it is copied, and new elements are added to the local copy inside add_contact .

Solution: follow the link

 void add_contact(list<Contact>& address_book). 
+2
source share

Say void add_contact(list<Contact> & address_book) to pass the address book by reference.

+1
source share

Pass by link

 void add_contact(list<Contact>& address_book). 
+1
source share

All Articles