I'm revising for an upcoming C++ exam in the next few days and looking at past paper answers, every time something simple like a get or set method is called, the parameters are passed as constant references.
Should I always be doing something like this unless I explicitly don't want constant references to take effect?
For example this:
class Person{
string name;
int age;
int niNo;
public:
Person(const string & _name, const int & _age, const int & ni) : name(_name), age(_age), niNo(ni) {}
string getName() const{
return name;
}
int getAge() const{
return age;
}
int getNi() const{
return niNo;
}
bool operator==(const Person &p){
return name == p.getName() && age == p.getAge() && niNo == p.getNi();
}
};
class Contacts{
vector<Person> persons;
public:
template <typename T>
void addNewEntry(const T &p){
persons.push_back(p);
}
template <typename T>
void printAllAges(const T &name){
for (int i = 0; i < persons.size(); ++i)
{
if (persons[i].getName() == name)
cout << persons[i].getAge() << endl;
}
}
};
I assume it's faster because passing by value would mean a temporary parameter object is made and the value copied to it. And the constant is just good practise to indicate the value won't be changed?
EDIT: Thanks for clarifying everyone, much appreciated.