Ampersand & with const in constructor

Madu picture Madu · Apr 3, 2012 · Viewed 7.1k times · Source

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.

Answer

spencercw picture spencercw · Apr 3, 2012

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.