I was wondering - why is putting const (...)&
in C++ a good idea? I found this code in some class tutorials. I understand that const
is making something constant and it can't be changed, while &
is passing it to the function. Why do both? If I can't change something, why should I be passing it to the function?
Here is an example:
class CVector {
public:
int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector& param) { //example
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change the value of const variable by using pointer ).
const prevents the variable to be assigned to another value. We could say it makes the pointer immutable, but it doesn't make the value immutable too!
A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.
const is only useful to enforce correctness, ie tell the compiler that if the developer directly modifies the object through the const reference, he is to be told off. An object does not become magically immutable when passed by a const reference. It is more of a guarantee by the programmer it will not be altered.
Even though the const
is keeping you from changing the value of your parameter, it's better to send a reference to it, rather than send it by value, because, in large objects, sending it by value would require copying it first, which is not necessary when calling by reference
It speeds up the code execution, it offers usage simplicity and it also ensures the caller that you can not change the value of the variable by setting const
keyword. It maybe have some other benefits, but I think the performance is the main reason. In this article and related articles, there are many useful things about References in C++.
When you pass a parameter by const type &
(pass by reference) like this:
void printStudent(const Student &s)
{
cout << s.name << " " << s.address << " " << s.rollNo;
}
int main(){
Student s1;
printStudent(s1);
return 0;
}
Benefits are:
s=new Student();
the compiler error will happen. So the caller can pass the variable with more confidence.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With