Can some body tell me the reason why we usually put const and & with some object which is passed in the constructor for example.
Book::Book(const Date &date);
The confusion that i have here is that usually & sign is used in the some function because the value is passed by reference and whatever changes happen to that variable in the function should reflect afterwards. But on the other hand const says that no assignment can be done to that variable.
If some body have some good idea about that please let me know the reason for that.
In c++, when you have a parameter type of a function be something like
const Type&
, what you are doing is allowing a user to pass some value in by reference - A pointer to the value is implicitly passed in, but for ease of use, the compiler allows you to treat it as if it was a value.In some cases, the compiler can also optimize it so that no pointer is used at all, and the function can refer directly to the memory of the value.
The reason that
const
is used is to safeguard yourself from altering memory that the user doesn't expect you to alter, and also to have it still work if the user passes in a const variable.A const reference is a way of passing the data to the class without copying the data to a local copy, and still guaranteeing that the original object won't be modified by the function.
It's typically a performance optimization for input parameters. If you omit the '&' the parameter is accepted by value and the input object will have to be copied before being passed to the function. Passing by reference bypasses the copy.
It means that you pass the object via refrence (as you noted), but the object itself cannot be changed from the function (ctor in this case).
The reason for this could be:
Date
in this case)For the third point, consider:
This is done to avoid an unnecessary copy. Take, for example, the following code:
When you call this constructor it will copy
date
twice, once when you call the constructor, and once when you copy it into your member variable.If you do this:
date
is only copied once. It is essentially just an optimisation.The most common alternative is to pass by value:
Passing by const reference prevents the parameter
date
from being copied when the parameter you pass is already aDate
. Copying objects can be unnecessary, can be costly to perform, or it could result in a sliced object (and the incorrect results).'Slicing' is basically demotion of an object's type via copy to its base. For a polymorphic type, this can actually change its behavior because the parameter would be copied as its base (
Date
), and then calls to its polymorphic interfaces would be different because the implementation has changed (e.g. its virtual methods would use the base's implementation instead).