A brother suggested me that I pass the arguments in the constructor and other member functions of the class by reference instead and even return references from member functions, so that it avoids copying of variables all the time. I'm a very naive programmer and don't know how best to do it. Can you please tell me how to apply it to the following program:
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(string s, int i) {
name = s;
id = i;
}
void setName(string s) {
name = s;
}
void setId(int i) {
id = i;
}
string getName() {
return name;
}
int returnId() {
return id;
}
private:
string name;
int id;
};
int main() {
Student s1("Seth",515);
}
This is what I did:
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(string& s, int& i) {
name = s;
id = i;
}
void setName(string& s) {
name = s;
}
void setId(int& i) {
id = i;
}
string& getName() {
return name;
}
int& returnId() {
return id;
}
private:
string name;
int id;
};
int main() {
string s = "John";
int i = 515;
Student s1(s,i);
return 0;
}
Is it alright to return reference variables, I mean don't they go out of scope in some cases?