Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ampersand & with const in constructor

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.

like image 741
Madu Avatar asked Apr 03 '12 18:04

Madu


3 Answers

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.

like image 124
spencercw Avatar answered Oct 22 '22 10:10

spencercw


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).

like image 6
justin Avatar answered Oct 22 '22 10:10

justin


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:

  • you do not want to copy the full object, to make your code more efficient
  • you do not want to accidentially change the passed-in object
  • you want to be able to use the function with unnamed temporaries
  • you want to be able to pass objects that derive from the noted type (Date in this case)

For the third point, consider:

Book b(Date());
like image 2
Attila Avatar answered Oct 22 '22 11:10

Attila