Help with constructor.

Jul 25, 2018 at 3:25pm
Hi, can these two codes be used interchangeably?
If not, what is the advantage of one over the other?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  
#include <iostream>
using namespace std;

class myClass {
	public:
		myClass(string nm) {
			setName(nm);
		}
		void setName(string x) {
			name = x;
		}
		string getName() {
			return name;
		}
	private:
		string name;
};

int main() {
	myClass ob1("David");
	cout << ob1.getName();
}


Or
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

#include <iostream>
using namespace std;

class myClass {
	public:
		myClass(string nm) {
			name = nm;
		}
		
		/*
		void setName(string x) {
			name = x;
		}
		*/
		
		string getName() {
			return name;
		}
	private:
		string name;
};

int main() {
	myClass ob1("David");
	cout << ob1.getName();
}
Jul 25, 2018 at 3:41pm
The function setName allows you to change the name even after the constructor has set name's value. Apart from that the code is identical. Just remember to #include <string>

Are there any advantages to one or the other? The first code gives you an easy way to fix a misspelled name. The second code on the other hand is more unchangeable if you don't want someone changing the value of name.
Last edited on Jul 25, 2018 at 3:41pm
Jul 25, 2018 at 3:58pm
Thank you!
So without having the setName function we wont be able to change the name later one and will be able to change it once and when the object is created.

I'm new to c++ and this forum and i am already loving getting fast responses here.
Jul 25, 2018 at 7:54pm
Well welcome, and stick around. You will learn a lot here.
Jul 25, 2018 at 8:10pm
also note that the constructor (example 1) reused set name, this is good. code reuse is better than repeating the code usually, even if trivial. That way if the logic changes you can fix it in one place (maybe you want to do nothing if they try to set it to empty string as a new requirement, for a silly example).

Topic archived. No new replies allowed.