Does anyone know why this will not display the name to the console? If I call A.getName(); in the addContact function itself it will retrieve the name correctly, however I believe it deletes itself after the function addContact ends. Can anyone spot where I went wrong?
Edit: I was able to make it print the name correctly, I still have a question though. How can I make it store more than one name?Code:#include <iostream> using namespace std; class Phonebook { private: string Name; public: void menu(); void setName(string); string getName(){return Name;} void addContact(Phonebook); void printContacts(Phonebook); }; void Phonebook::menu(){ cout << "Phonebook Menu" << endl; cout << "(1) Add Contact" << endl; cout << "Choose an option: "; } void Phonebook::setName(string s){ Name = s; } void Phonebook::addContact(Phonebook A){ string s; cout << "\n\n[Add Contact]" << endl; cout << "Name: "; cin >> s; A.setName(s); } void Phonebook::printContacts(Phonebook A){ cout << "\n\n[Contact List]" << endl; cout << A.getName() << endl; } int main(){ Phonebook A; int option = 0; A.menu(); cin >> option; switch(option){ case 1: A.addContact(A); A.printContacts(A); break; } return 0; }
New Code:
Code:#include <iostream> using namespace std; class Phonebook { private: string Name; public: void menu(); void setName(string); string getName(){return Name;} void addContact(Phonebook *); void printContacts(Phonebook); }; void Phonebook::menu(){ cout << "Phonebook Menu" << endl; cout << "(1) Add Contact" << endl; cout << "Choose an option: "; } void Phonebook::setName(string s){ Name = s; } void Phonebook::addContact(Phonebook * A){ string s; cout << "\n\n[Add Contact]" << endl; cout << "Name: "; cin >> s; A->setName(s); } void Phonebook::printContacts(Phonebook A){ cout << "\n\n[Contact List]" << endl; cout << A.getName() << endl; } int main(){ Phonebook A; int option = 0; A.menu(); cin >> option; switch(option){ case 1: A.addContact(&A); A.printContacts(A); break; } return 0; }