Should I use getters and setters, or just use a constructor?

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
 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;

	const int 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
	}
}
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.