Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the copy-constructor argument const?

 Vector(const Vector& other) // Copy constructor   {     x = other.x;     y = other.y; 

Why is the argument a const?

like image 623
unj2 Avatar asked Oct 21 '09 16:10

unj2


People also ask

What is the correct argument for copy constructor?

Definition. Copying of objects is achieved by the use of a copy constructor and an assignment operator. A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.

What is copy const Why do we use & in copy CTR parameters list?

Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.

Why we Cannot pass the argument by value to a copy constructor?

A copy constructor cannot receive value by call by value method. While we invoke copy constructor an object of same class must be passed to it. But the object passed need to be copied in formal arguments.

Can constructors be constant?

Constructors and destructors can never be declared to be const . They are always allowed to modify an object even if the object itself is constant.


2 Answers

You've gotten answers that mention ensuring that the ctor can't change what's being copied -- and they're right, putting the const there does have that effect.

More important, however, is that a temporary object cannot bind to a non-const reference. The copy ctor must take a reference to a const object to be able to make copies of temporary objects.

like image 196
Jerry Coffin Avatar answered Sep 20 '22 01:09

Jerry Coffin


Because you are not going to modify the argument other inside the copy ctor as it is const.

When you did x = other.x it essentially means this->x = other.x. So you are modifying only this object just by copying the values from other variable. Since the other variable is read-only here, it is passed as a const-ref.

like image 22
Naveen Avatar answered Sep 23 '22 01:09

Naveen