18

I'm trying to build a very simple address book. I created a Contact class and the address book is a simple list. I'm trying to build a function to allow the user to add contacts to the address book. If I take my code outside of the function, it works OK. However, if I put it in, it doesn't work. I believe it's a passing by reference vs passing by value problem which I'm not treating as I 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 don't get any errors however when I try to display all contacts, I can see only the original ones.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Adrian
  • 609
  • 2
  • 11
  • 22

4 Answers4

16

You're passing address_book by value, so a copy of what you pass in is made and when you leave the scope of add_contact your changes are lost.

Pass by reference instead:

void add_contact(list<Contact>& address_book)
ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • Is every STL DS is pass by value? – Rahul Jan 21 '21 at 13:12
  • @Rahul : C++ as a language has [_value semantics_](https://isocpp.org/wiki/faq/value-vs-ref-semantics) – passing by value vs. by reference is decided on a per-function, not per-type, basis. – ildjarn Jan 21 '21 at 14:29
2

Because you are passing list by value, thus it is copied, and new elements are added to a local copy inside add_contact.

Solution: pass by reference

void add_contact(list<Contact>& address_book).
Krizz
  • 11,362
  • 1
  • 30
  • 43
1

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

Pass by reference

void add_contact(list<Contact>& address_book).