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.
This is done to avoid an unnecessary copy. Take, for example, the following code:
Book::Book(Date date):
date_(date)
{
}
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:
Book::Book(const Date &date):
date_(date)
{
}
date
is only copied once. It is essentially just an optimisation.
The most common alternative is to pass by value:
Book::Book(Date date);
Passing by const reference prevents the parameter date
from being copied when the parameter you pass is already a Date
. 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).
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:
Book b(Date());
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