In the code below, I have a (set of) getters and a (set of) setters. Above my getters and setters I have a constructor that does (from my understanding) the exact same thing as the getters and setters do. My question is, why in the heck should I ever use a getter or setter if I can make a constructor that does the exact same thing?
class Person
{
private:
string _name;
string _number;
string _address;
public:
//constructor that initializes all the private variables using parameters
//supplied by whoever invokes this constructor
Person(string newName, string newNumber, string newAddress)
: _name(newName), _number(newNumber), _address(newAddress)
{ }
/* We cannot access any of our members in our private class since they are all set to private by default,
so we need getters and setters to access them.*/
// getters
// getters are also used to restrict what the user can see
string get_Name()
{
return _name;
}
string get_Address()
{
return _address;
}
string get_Number()
{
return _number;
}
//setters
// setters are also used to restrict what the user can change.
void set_Name(string N)
{
_name = N;
}
void set_Address(string A)
{
_address = A;
}
void set_Number(string N)
{
_number = N
}
};
class AddressBook
{
private:
vector<Person> _people;
public:
void addPerson(const Person& p)
{
_people.push_back(p);
}
};
int main()
{
AddressBook myAddBook;
constint numPeopleInBook = 2;
for (int i = 0; i < numPeopleInBook; ++i)
{
string nameFromUser, addressFromUser, numberFromUser;
cout << "Give me a name: ";
getline(cin, nameFromUser);
cout << "Give me a number: ";
getline(cin, numberFromUser);
cout << "Give me an address: ";
getline(cin, addressFromUser);
Person p(nameFromUser, numberFromUser, addressFromUser);
myAddBook.addPerson(p); // pushes the name, number, and address back into the vector
}
}
Constructors are used so that an object is (in most cases) in a usable state as soon as its declared (this can't always happen, but it's the ideal).
Setters/Getters are used to change/access an object's properties after its already been initialized through the constructor.
Sure, in your program's use case, the setters/getters have little use, but if you wanted to have a function that iterated through every Person in your Address Book to update contact info or something, that's when you would want to use a setter, or using getters to print out each Person's name / number in the Address Book.